removed cruft, fixed ptset.ml
[SXSI/xpathcomp.git] / ata.ml
1 INCLUDE "debug.ml"
2 INCLUDE "utils.ml"
3
4
5
6 type jump_kind = [ `TAG of Tag.t | `CONTAINS of string | `NOTHING ]
7
8 (* Todo : move elsewhere *)
9 external vb : bool -> int = "%identity"
10
11 module State : 
12 sig 
13   include Sigs.T with type t = int 
14   val make : unit -> t 
15 end =
16 struct
17   type t = int
18   let make = 
19     let id = ref (-1) in
20       fun () -> incr id;!id
21   let compare = (-)
22   let equal = (==)
23   external hash : t -> int =  "%identity"
24   let print fmt x = Format.fprintf fmt "%i" x
25   let dump fmt x = print fmt x
26   let check x = 
27     if x < 0 then failwith (Printf.sprintf "State: Assertion %i < 0 failed" x)
28 end
29
30 module StateSet = struct
31   include Ptset.Int
32   let print ppf s = 
33     Format.pp_print_string ppf "{ ";
34     iter (fun i -> Format.fprintf ppf "%i " i) s;
35     Format.pp_print_string ppf "}";
36     Format.pp_print_flush ppf ()
37 end
38   
39 module Formula =
40 struct
41     type 'hcons expr = 
42       | False | True
43       | Or of 'hcons * 'hcons
44       | And of 'hcons * 'hcons
45       | Atom of ([ `Left | `Right  | `LLeft | `RRight  ]*bool*State.t)
46     type 'hcons node = {
47       pos : 'hcons expr;
48       mutable neg : 'hcons;
49       st : (StateSet.t*StateSet.t*StateSet.t)*(StateSet.t*StateSet.t*StateSet.t);
50       size: int; (* Todo check if this is needed *)
51     }
52         
53     external hash_const_variant : [> ] -> int = "%identity" 
54     module rec HNode : Hcons.S with type data = Node.t = Hcons.Make (Node)
55     and Node : Hashtbl.HashedType  with type t = HNode.t node =
56     struct 
57     type t =  HNode.t node
58     let equal x y = x.size == y.size &&
59       match x.pos,y.pos with
60       | False,False
61       | True,True -> true
62       | Or(xf1,xf2),Or(yf1,yf2) 
63       | And(xf1,xf2),And(yf1,yf2)  -> (HNode.equal xf1 yf1) && (HNode.equal xf2 yf2)
64       | Atom(d1,p1,s1), Atom(d2,p2,s2) -> d1 == d2 && (p1==p2) && s1 == s2
65       | _ -> false
66     let hash f = 
67       match f.pos with
68         | False -> 0
69         | True -> 1
70         | Or (f1,f2) -> HASHINT3(PRIME2,HNode.hash f1,HNode.hash f2)
71         | And (f1,f2) -> HASHINT3(PRIME3,HNode.hash f1,HNode.hash f2)
72         | Atom(d,p,s) -> HASHINT4(PRIME4,hash_const_variant d,vb p,s)       
73     end
74
75     type t = HNode.t
76     let hash = HNode.hash 
77     let uid = HNode.uid 
78     let equal = HNode.equal 
79     let expr f = (HNode.node f).pos
80     let st f = (HNode.node f ).st
81     let size f = (HNode.node f).size
82       
83     let prio f = 
84       match expr f with
85         | True | False -> 10
86         | Atom _ -> 8
87         | And _ -> 6
88         | Or _ -> 1
89
90     let rec print ?(parent=false) ppf f =
91       if parent then Format.fprintf ppf "(";
92       let _ = match expr f with
93         | True -> Format.fprintf ppf "T"
94         | False -> Format.fprintf ppf "F"
95         | And(f1,f2) -> 
96             print ~parent:(prio f > prio f1) ppf f1;
97             Format.fprintf ppf " ∧ ";
98             print ~parent:(prio f > prio f2) ppf f2;
99         | Or(f1,f2) -> 
100             (print ppf f1);
101             Format.fprintf ppf " ∨ ";
102             (print ppf f2);
103         | Atom(dir,b,s) -> Format.fprintf ppf "%s%s[%i]"
104             (if b then "" else "¬")
105               (match  dir with 
106                  | `Left ->  "↓₁" 
107                  | `Right -> "↓₂"
108                  | `LLeft ->  "⇓₁" 
109                  | `RRight -> "⇓₂") s
110       in
111         if parent then Format.fprintf ppf ")"
112           
113     let print ppf f =  print ~parent:false ppf f
114       
115     let is_true f = (expr f) == True
116     let is_false f = (expr f) == False
117
118
119     let cons pos neg s1 s2 size1 size2 =
120       let nnode = HNode.make { pos = neg; neg = (Obj.magic 0); st = s2; size = size2 } in
121       let pnode = HNode.make { pos = pos; neg = nnode ; st = s1; size = size1 }
122       in 
123         (HNode.node nnode).neg <- pnode; (* works because the neg field isn't taken into
124                                             account for hashing ! *)
125         pnode,nnode
126
127     let empty_triple = StateSet.empty,StateSet.empty,StateSet.empty
128     let empty_hex = empty_triple,empty_triple
129     let true_,false_ = cons True False empty_hex empty_hex 0 0
130     let atom_ d p s = 
131       let si = StateSet.singleton s in
132       let ss = match d with
133         | `Left -> (si,StateSet.empty,si),empty_triple
134         | `Right -> empty_triple,(si,StateSet.empty,si)
135         | `LLeft -> (StateSet.empty,si,si),empty_triple
136         | `RRight -> empty_triple,(StateSet.empty,si,si)
137       in fst (cons (Atom(d,p,s)) (Atom(d,not p,s)) ss ss 1 1)
138
139     let not_ f = (HNode.node f).neg
140     let union_hex  ((l1,ll1,lll1),(r1,rr1,rrr1))  ((l2,ll2,lll2),(r2,rr2,rrr2)) =
141       (StateSet.mem_union l1 l2 ,StateSet.mem_union ll1 ll2,StateSet.mem_union lll1 lll2),
142       (StateSet.mem_union r1 r2 ,StateSet.mem_union rr1 rr2,StateSet.mem_union rrr1 rrr2)
143       
144     let merge_states f1 f2 =
145       let sp = 
146         union_hex (st f1) (st f2)
147       and sn = 
148         union_hex (st (not_ f1)) (st (not_ f2))
149       in
150         sp,sn
151
152     let order f1 f2 = if uid f1  < uid f2 then f2,f1 else f1,f2 
153
154     let or_ f1 f2 = 
155       (* Tautologies: x|x, x|not(x) *)
156
157       if equal f1 f2 then f1 else        
158       if equal f1 (not_ f2) then true_ else
159
160       (* simplification *)
161       if is_true f1 || is_true f2 then true_ else
162       if is_false f1 && is_false f2 then false_ else
163       if is_false f1 then f2 else
164       if is_false f2 then f1 else
165
166       (* commutativity of | *)
167       
168       let f1,f2 = order f1 f2 in
169       let psize = (size f1) + (size f2) in
170       let nsize = (size (not_ f1)) + (size (not_ f2)) in
171       let sp,sn = merge_states f1 f2 in
172         fst (cons (Or(f1,f2)) (And(not_ f1,not_ f2)) sp sn psize nsize)
173               
174                       
175     let and_ f1 f2 = 
176
177       (* Tautologies: x&x, x&not(x) *)
178
179       if equal f1 f2 then f1 else 
180       if equal f1 (not_ f2) then false_ else
181
182         (* simplifications *)
183
184       if is_true f1 && is_true f2 then true_ else
185       if is_false f1 || is_false f2 then false_ else
186       if is_true f1 then f2 else
187       if is_true f2 then f1 else
188       
189       (* commutativity of & *)
190
191       let f1,f2 = order f1 f2 in        
192       let psize = (size f1) + (size f2) in
193       let nsize = (size (not_ f1)) + (size (not_ f2)) in
194       let sp,sn = merge_states f1 f2 in
195         fst (cons (And(f1,f2)) (Or(not_ f1,not_ f2)) sp sn psize nsize)               
196     module Infix = struct
197     let ( +| ) f1 f2 = or_ f1 f2
198     let ( *& ) f1 f2 = and_ f1 f2
199     let ( *+ ) d s = atom_ d true s
200     let ( *- ) d s = atom_ d false s
201     end
202 end
203   
204 module Transition = struct
205   
206   type node = State.t*bool*Formula.t*bool
207   include Hcons.Make(struct
208                        type t = node
209                        let hash (s,m,f,b) = HASHINT4(s,Formula.uid f,vb m,vb b)
210                        let equal (s,b,f,m) (s',b',f',m') = 
211                          s == s' && b==b' && m==m' && Formula.equal f f' 
212                      end)
213     
214   let print ppf f = let (st,mark,form,b) = node f in
215     Format.fprintf ppf "%i %s" st (if mark then "⇒" else "→");
216     Formula.print ppf form;
217     Format.fprintf ppf "%s%!" (if b then " (b)" else "")
218
219
220   module Infix = struct
221   let ( ?< ) x = x
222   let ( >< ) state (l,mark) = state,(l,mark,false)
223   let ( ><@ ) state (l,mark) = state,(l,mark,true)
224   let ( >=> ) (state,(label,mark,bur)) form = (state,label,(make (state,mark,form,bur)))
225   end
226
227 end
228
229 module SetTagKey =
230 struct 
231   type t = Ptset.Int.t*Tag.t 
232   let equal (s1,t1) (s2,t2) =  (t1 == t2) &&  Ptset.Int.equal s1 s2
233   let hash (s,t) = HASHINT2(Ptset.Int.hash s,Tag.hash t)
234 end
235
236 module TransTable = Hashtbl
237 module CachedTransTable = Hashtbl.Make(SetTagKey)
238  
239 module Formlist = struct 
240   include Ptset.Make(Transition)
241   let print ppf fl = 
242     iter (fun t -> Transition.print ppf t; Format.pp_print_newline ppf ()) fl
243 end
244
245   
246 type 'a t = { 
247     id : int;
248     mutable states : Ptset.Int.t;
249     init : Ptset.Int.t;
250     starstate : Ptset.Int.t option;
251     (* Transitions of the Alternating automaton *)
252     trans : (State.t,(TagSet.t*Transition.t) list) Hashtbl.t;
253     query_string: string;
254  }
255
256         
257 let dump ppf a = 
258   Format.fprintf ppf "Automaton (%i) :\n" a.id;
259   Format.fprintf ppf "States : "; StateSet.print ppf a.states;
260   Format.fprintf ppf "\nInitial states : "; StateSet.print ppf a.init;
261   Format.fprintf ppf "\nAlternating transitions :\n";
262   let l = Hashtbl.fold (fun k t acc -> 
263                           (List.map (fun (ts,tr) -> (ts,k),Transition.node tr) t) @ acc) a.trans [] in
264   let l = List.sort (fun ((tsx,x),_) ((tsy,y),_) -> 
265                        if y-x == 0 then TagSet.compare tsy tsx else y-x) l in
266   let maxh,maxt,l_print = 
267     List.fold_left (
268       fun (maxh,maxt,l) ((ts,q),(_,b,f,_)) ->                     
269         let s = 
270           if TagSet.is_finite ts 
271           then "{" ^ (TagSet.fold (fun t a -> a ^ " '" ^ (Tag.to_string t)^"'") ts "") ^" }"
272           else let cts = TagSet.neg ts in
273             if TagSet.is_empty cts then "*" else
274             (TagSet.fold (fun t a -> a ^ " " ^ (Tag.to_string t)) cts "*\\{"
275             )^ "}"
276         in
277         let s = Printf.sprintf "(%s,%i)" s q in
278         let s_frm =
279           Formula.print Format.str_formatter f;
280           Format.flush_str_formatter()     
281         in
282           (max (String.length s) maxh, max (String.length s_frm) maxt,
283            (s,(if b then "⇒" else "→"),s_frm)::l)) (0,0,[]) l
284   in
285     Format.fprintf ppf "%s\n%!" (String.make (maxt+maxh+3) '_');
286     List.iter (fun (s,m,f) -> let s = s ^ (String.make (maxh-(String.length s)) ' ') in
287                  Format.fprintf ppf "%s %s %s\n" s m f) l_print;
288     Format.fprintf ppf "%s\n%!" (String.make (maxt+maxh+3) '_')
289     
290
291 module MemoForm = Memoizer.Make(
292   Hashtbl.Make(struct
293                  type t = Formula.t*(StateSet.t*StateSet.t)
294                  let equal (f1,(s1,t1)) (f2,(s2,t2)) =
295                    Formula.equal f1 f2 && StateSet.equal s1 s2 && StateSet.equal t1 t2
296                  let hash (f,(s,t)) = 
297                    HASHINT3(Formula.uid f ,StateSet.uid s,StateSet.uid t)
298                end))
299       
300 module F = Formula
301
302     let eval_form_bool f s1 s2 =   
303       let sets = (s1,s2) in
304       let eval = MemoForm.make_rec( 
305         fun eval (f,_) ->
306           match F.expr f with
307             | F.True -> true,true,true
308             | F.False -> false,false,false
309             | F.Atom((`Left|`LLeft),b,q) ->
310                 if b == (StateSet.mem q s1) 
311                 then (true,true,false) 
312                 else false,false,false
313             | F.Atom(_,b,q) -> 
314                 if b == (StateSet.mem q s2) 
315                 then (true,false,true)
316                 else false,false,false                  
317             | F.Or(f1,f2) ->        
318                 let b1,rl1,rr1 = eval (f1,sets)
319                 in
320                   if b1 && rl1 && rr1 then (true,true,true)  else
321                   let b2,rl2,rr2 = eval (f2,sets)  in
322                   let rl1,rr1 = if b1 then rl1,rr1 else false,false
323                   and rl2,rr2 = if b2 then rl2,rr2 else false,false
324                   in (b1 || b2, rl1||rl2,rr1||rr2)
325
326         | F.And(f1,f2) -> 
327             let b1,rl1,rr1 = eval (f1,sets) in
328               if b1 && rl1 && rr1 then (true,true,true) else
329               if b1 then 
330               let b2,rl2,rr2 = eval (f2,sets) in
331                 if b2 then (true,rl1||rl2,rr1||rr2) else (false,false,false)
332               else (false,false,false)      
333       )
334       in
335         eval (f,sets)
336
337
338     module MemoFormlist = Memoizer.Make(
339       Hashtbl.Make(struct
340                      type t = Formlist.t*(StateSet.t*StateSet.t)
341                      let equal (f1,(s1,t1)) (f2,(s2,t2)) =
342                        Formlist.equal f1 f2 && StateSet.equal s1 s2 && StateSet.equal t1 t2
343                      let hash (f,(s,t)) = 
344                        HASHINT3(Formlist.uid f ,StateSet.uid s,StateSet.uid t)
345                    end))
346
347     let eval_formlist ?(memo=true) s1 s2 fl = 
348       let sets = (s1,s2) in
349       let eval = MemoFormlist.make_rec (
350         fun eval (fl,_) ->
351           if Formlist.is_empty fl 
352           then StateSet.empty,false,false,false,false
353           else 
354           let f,fll = Formlist.uncons fl in
355           let q,mark,f,_ = Transition.node f in
356           let b,b1,b2 = eval_form_bool f s1 s2 in
357           let s,b',b1',b2',amark = eval (fll,sets) in
358             if b then (StateSet.add q s, b, b1'||b1,b2'||b2,mark||amark)
359             else s,b',b1',b2',amark )
360       in eval (fl,sets)
361               
362               
363     let tags_of_state a q = 
364       Hashtbl.fold  
365         (fun p l acc -> 
366            if p == q then List.fold_left 
367              (fun acc (ts,t) -> 
368                 let _,_,_,aux = Transition.node t in
369                   if aux then acc else
370                     TagSet.cup ts acc) acc l
371            
372            else acc) a.trans TagSet.empty
373       
374       
375
376     let tags a qs = 
377       let ts = Ptset.Int.fold (fun q acc -> TagSet.cup acc (tags_of_state a q)) qs TagSet.empty
378       in
379         if TagSet.is_finite ts 
380         then `Positive(TagSet.positive ts)
381         else `Negative(TagSet.negative ts)
382         
383     let inter_text a b =
384       match b with
385         | `Positive s -> let r = Ptset.Int.inter a s in (r,Ptset.Int.mem Tag.pcdata r, true)
386         | `Negative s -> let r = Ptset.Int.diff a s in (r, Ptset.Int.mem Tag.pcdata r, false)
387
388     let mk_nil_ctx x _ = Tree.mk_nil x
389     let next_sibling_ctx x _ = Tree.next_sibling x 
390     let r_ignore _ x = x
391       
392
393     module type ResultSet = 
394     sig
395       type t
396       val empty : t
397       val cons : Tree.t -> t -> t
398       val concat : t -> t -> t
399       val iter : (Tree.t -> unit) -> t -> unit
400       val fold : (Tree.t -> 'a -> 'a) -> t -> 'a -> 'a
401       val map : (Tree.t -> Tree.t) -> t -> t
402       val length : t -> int
403     end
404
405     module Integer : ResultSet =
406     struct
407       type t = int
408       let empty = 0
409       let cons _ x = x+1
410       let concat x y = x + y
411       let iter _ _ = failwith "iter not implemented"
412       let fold _ _ _ = failwith "fold not implemented"
413       let map _ _ = failwith "map not implemented"
414       let length x = x
415     end
416
417     module IdSet : ResultSet = 
418     struct
419       type node = Nil 
420                   | Cons of Tree.t * node 
421                   | Concat of node*node
422    
423       and t = { node : node;
424                 length :  int }
425
426       let empty = { node = Nil; length = 0 }
427         
428       let cons e t = { node = Cons(e,t.node); length = t.length+1 }
429       let concat t1 t2 = { node = Concat(t1.node,t2.node); length = t1.length+t2.length }
430       let append e t = { node = Concat(t.node,Cons(e,Nil)); length = t.length+1 } 
431         
432       let fold f l acc = 
433         let rec loop acc t = match t with
434           | Nil -> acc
435           | Cons (e,t) -> loop (f e acc) t
436           | Concat (t1,t2) -> loop (loop acc t1) t2
437         in
438           loop acc l.node
439             
440       let length l = l.length
441         
442         
443       let iter f l =
444         let rec loop = function
445           | Nil -> ()
446           | Cons (e,t) -> f e; loop t
447           | Concat(t1,t2) -> loop t1;loop t2
448         in loop l.node
449
450       let map f l =
451         let rec loop = function 
452           | Nil -> Nil
453           | Cons(e,t) -> Cons(f e, loop t)
454           | Concat(t1,t2) -> Concat(loop t1,loop t2)
455         in
456           { l with node = loop l.node }
457
458            
459     end
460
461     module Run (RS : ResultSet) =
462     struct
463
464
465       let fmt = Format.err_formatter
466       let pr x = Format.fprintf fmt x
467         
468       type ptset_list = Nil | Cons of Ptset.Int.t*int*ptset_list
469       let hpl l = match l with
470         | Nil -> 0
471         | Cons (_,i,_) -> i 
472
473       let cons s l = Cons (s,(Ptset.Int.hash s) + 65599 * (hpl l), l)
474           
475       let rec empty_size n = 
476         if n == 0 then Nil
477         else cons Ptset.Int.empty (empty_size (n-1))
478         
479       let fold_pl f l acc = 
480         let rec loop l acc = match l with
481             Nil -> acc
482           | Cons(s,h,pl) -> loop pl (f s h acc)
483         in
484           loop l acc
485       let map_pl f l = 
486         let rec loop =
487           function Nil -> Nil 
488             | Cons(s,h,ll) -> cons (f s) (loop ll) 
489         in loop l
490       let iter_pl f l = 
491         let rec loop =
492           function Nil -> ()
493             | Cons(s,h,ll) ->  (f s);(loop ll) 
494         in loop l
495
496       let rev_pl l = 
497         let rec loop acc l = match l with 
498           | Nil -> acc
499           | Cons(s,_,ll) -> loop (cons s acc) ll
500         in
501           loop Nil l
502
503       let rev_map_pl f l  = 
504         let rec loop acc l = 
505           match l with 
506             | Nil -> acc
507             | Cons(s,_,ll) -> loop (cons (f s) acc) ll
508         in
509           loop Nil l
510
511       module IntSet = Set.Make(struct type t = int let compare = (-) end)
512
513
514 IFDEF DEBUG
515 THEN
516 INCLUDE "html_trace.ml"
517               
518 END             
519
520       let td_trans = Hashtbl.create 4096
521       let mk_fun f s = D_IGNORE_(register_funname f s,f)
522       let mk_app_fun f arg s = let g = f arg in 
523         D_IGNORE_(register_funname g ((get_funname f) ^ " " ^ s), g) 
524
525       let string_of_ts tags = (Ptset.Int.fold (fun t a -> a ^ " " ^ (Tag.to_string t) ) tags "{")^ " }"
526         
527       let choose_jump tagset qtags1 qtagsn a f_nil f_text f_t1 f_s1 f_tn f_sn f_notext =
528         let tags1,hastext1,fin1 = inter_text tagset (tags a qtags1) in
529         let tagsn,hastextn,finn = inter_text tagset (tags a qtagsn) in
530           if (hastext1||hastextn) then f_text  (* jumping to text nodes doesn't work really well *)
531           else if (Ptset.Int.is_empty tags1) && (Ptset.Int.is_empty tagsn) then f_nil
532           else if (Ptset.Int.is_empty tagsn) then 
533             if (Ptset.Int.is_singleton tags1) 
534             then (* TaggedChild/Sibling *)
535               let tag = (Ptset.Int.choose tags1) in mk_app_fun f_t1 tag (Tag.to_string tag)
536             else (* SelectChild/Sibling *)
537               mk_app_fun f_s1 tags1 (string_of_ts tags1)
538           else if (Ptset.Int.is_empty tags1) then 
539             if (Ptset.Int.is_singleton tagsn) 
540             then (* TaggedDesc/Following *)
541               let tag = (Ptset.Int.choose tagsn) in  mk_app_fun f_tn tag (Tag.to_string tag)
542             else (* SelectDesc/Following *)
543               mk_app_fun f_sn tagsn (string_of_ts tagsn) 
544           else f_notext
545           
546       let choose_jump_down a b c d =
547         choose_jump a b c d
548           (mk_fun (Tree.mk_nil) "Tree.mk_nil")
549           (mk_fun (Tree.text_below) "Tree.text_below")
550           (mk_fun (fun _ -> Tree.node_child) "[TaggedChild]Tree.node_child") (* !! no tagged_child in Tree.ml *)
551           (mk_fun (fun _ -> Tree.node_child) "[SelectChild]Tree.node_child") (* !! no select_child in Tree.ml *)
552           (mk_fun (Tree.tagged_desc) "Tree.tagged_desc")
553           (mk_fun (fun _ -> Tree.node_child ) "[SelectDesc]Tree.node_child") (* !! no select_desc *)
554           (mk_fun (Tree.node_child) "Tree.node_child")
555
556       let choose_jump_next a b c d = 
557         choose_jump a b c d
558           (mk_fun (fun t _ -> Tree.mk_nil t) "Tree.mk_nil2")
559           (mk_fun (Tree.text_next) "Tree.text_next")
560           (mk_fun (fun _ -> Tree.node_sibling_ctx) "[TaggedSibling]Tree.node_sibling_ctx")(* !! no tagged_sibling in Tree.ml *)
561           (mk_fun (fun _ -> Tree.node_sibling_ctx) "[SelectSibling]Tree.node_sibling_ctx")(* !! no select_sibling in Tree.ml *)
562           (mk_fun (Tree.tagged_foll_ctx) "Tree.tagged_foll_ctx")
563           (mk_fun (fun _ -> Tree.node_sibling_ctx) "[SelectFoll]Tree.node_sibling_ctx")(* !! no select_foll *)
564           (mk_fun (Tree.node_sibling_ctx) "Tree.node_sibling_ctx")        
565                                 
566       let get_trans slist tag a t = 
567         try 
568           Hashtbl.find td_trans (tag,hpl slist)
569         with
570           | Not_found -> 
571               let fl_list,llist,rlist,ca,da,sa,fa = 
572                 fold_pl 
573                   (fun set _  (fll_acc,lllacc,rllacc,ca,da,sa,fa) -> (* For each set *)
574                      let fl,ll,rr,ca,da,sa,fa = 
575                        StateSet.fold
576                          (fun q acc ->                      
577                             List.fold_left 
578                               (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc) 
579                                  (ts,t)  ->
580                                    if (TagSet.mem tag ts)
581                                    then 
582                                    let _,_,f,_ = Transition.node t in
583                                    let (child,desc,below),(sibl,foll,after) = Formula.st f in
584                                      (Formlist.add t fl_acc,
585                                       StateSet.union ll_acc below,
586                                       StateSet.union rl_acc after,
587                                       StateSet.union child c_acc,
588                                       StateSet.union desc d_acc,
589                                       StateSet.union sibl s_acc,
590                                       StateSet.union foll f_acc)                 
591                                    else acc ) acc (
592                                 try Hashtbl.find a.trans q 
593                                 with
594                                     Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
595                                       q;[]
596                               )
597                               
598                          ) set (Formlist.empty,StateSet.empty,StateSet.empty,ca,da,sa,fa)
599                      in fl::fll_acc, cons ll lllacc, cons rr rllacc,ca,da,sa,fa)
600                   slist ([],Nil,Nil,StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
601               in
602                 (* Logic to chose the first and next function *)
603               let tags_below,tags_after = Tree.tags t tag in
604               let first = choose_jump_down tags_below ca da a
605               and next = choose_jump_next tags_after sa fa a in 
606               let v = (fl_list,llist,rlist,first,next) in
607                 Hashtbl.add td_trans (tag, hpl slist) v; v
608                   
609       let merge rb rb1 rb2 mark t res1 res2 = 
610         if rb 
611         then 
612           let res1 = if rb1 then res1 else RS.empty
613           and res2 = if rb2 then res2 else RS.empty
614           in
615             if mark then RS.cons t (RS.concat res1 res2)
616             else RS.concat res1 res2
617         else RS.empty 
618
619       let top_down ?(noright=false) a t slist ctx slot_size =   
620         let pempty = empty_size slot_size in    
621         let eval_fold2_slist fll sl1 sl2 res1 res2 t =
622           let res = Array.copy res1 in
623           let rec fold l1 l2 fll i aq = match l1,l2,fll with
624             | Cons(s1,_,ll1), Cons(s2, _ ,ll2),fl::fll -> 
625                 let r',rb,rb1,rb2,mark = eval_formlist s1 s2 fl in
626                 let _ = res.(i) <- merge rb rb1 rb2 mark t res1.(i) res2.(i) 
627                 in                
628                   fold ll1 ll2 fll (i+1) (cons r' aq)
629             | Nil, Nil,[] -> aq,res
630             | _ -> assert false
631           in
632             fold sl1 sl2 fll 0 Nil
633         in
634         let null_result() = (pempty,Array.make slot_size RS.empty) in
635         let rec loop t slist ctx = 
636           if Tree.is_nil t then null_result()
637           else      
638             let tag = Tree.tag t in        
639             let fl_list,llist,rlist,first,next = get_trans slist tag a t in
640             let sl1,res1 = loop (first t) llist t in
641             let sl2,res2 = loop (next t ctx) rlist ctx in
642             let res = eval_fold2_slist fl_list sl1 sl2 res1 res2 t          
643             in
644               D_IGNORE_(
645                 register_trace t (slist,(fst res),sl1,sl2,fl_list,first,next,ctx),
646                 res)
647         in
648         let loop_no_right t slist ctx =
649           if Tree.is_nil t then null_result()
650           else      
651             let tag = Tree.tag t in
652             let fl_list,llist,rlist,first,next = get_trans slist tag a t in
653             let sl1,res1 = loop (first t) llist t in
654             let sl2,res2 = null_result() in
655             let res = eval_fold2_slist fl_list sl1 sl2 res1 res2 t
656             in  
657               D_IGNORE_(
658                 register_trace t (slist,(fst res),sl1,sl2,fl_list,first,next,ctx),
659                 res)
660         in
661           (if noright then loop_no_right else loop) t slist ctx
662             
663
664         let run_top_down a t =
665           let init = cons a.init Nil in
666           let _,res = top_down a t init t 1 
667           in 
668             D_IGNORE_(
669               output_trace a t "trace.html"
670                 (RS.fold (fun t a -> IntSet.add (Tree.id t) a) res.(0) IntSet.empty),
671               res.(0))
672         ;;
673
674         module Configuration =
675         struct
676           module Ptss = Set.Make(StateSet)
677           module IMap = Map.Make(StateSet)
678           type t = { hash : int;
679                         sets : Ptss.t;
680                         results : RS.t IMap.t }
681           let empty = { hash = 0;
682                         sets = Ptss.empty;
683                         results = IMap.empty;
684                       }
685           let is_empty c = Ptss.is_empty c.sets
686           let add c s r =
687             if Ptss.mem s c.sets then
688               { c with results = IMap.add s (RS.concat r (IMap.find s c.results)) c.results}
689             else
690               { hash = HASHINT2(c.hash,Ptset.Int.hash s);
691                 sets = Ptss.add s c.sets;
692                 results = IMap.add s r c.results
693               }
694
695           let pr fmt c = Format.fprintf fmt "{";
696             Ptss.iter (fun s -> StateSet.print fmt s;
697                         Format.fprintf fmt "  ") c.sets;
698             Format.fprintf fmt "}\n%!";
699             IMap.iter (fun k d -> 
700                          StateSet.print fmt k;
701                          Format.fprintf fmt "-> %i\n" (RS.length d)) c.results;                  
702             Format.fprintf fmt "\n%!"
703             
704           let merge c1 c2  =
705             let acc1 = IMap.fold (fun s r acc -> 
706                                     IMap.add s
707                                       (try 
708                                          RS.concat r (IMap.find s acc)
709                                        with
710                                          | Not_found -> r) acc) c1.results IMap.empty 
711             in
712             let imap =
713               IMap.fold (fun s r acc -> 
714                            IMap.add s
715                              (try 
716                                 RS.concat r (IMap.find s acc)
717                               with
718                                 | Not_found -> r) acc)  c2.results acc1
719             in
720             let h,s =
721               Ptss.fold 
722                 (fun s (ah,ass) -> (HASHINT2(ah,Ptset.Int.hash s),
723                                     Ptss.add s ass))
724                 (Ptss.union c1.sets c2.sets) (0,Ptss.empty)
725             in
726               { hash = h;
727                 sets =s;
728                 results = imap }
729
730         end
731
732         let h_fold = Hashtbl.create 511 
733
734         let fold_f_conf  t slist fl_list conf dir= 
735           let rec loop sl fl acc =
736             match sl,fl with
737               |Nil,[] -> acc
738               | Cons(s,hs,sll), formlist::fll ->
739                   let r',rb,rb1,rb2,mark = 
740                     try 
741                       Hashtbl.find h_fold (hs,Formlist.hash formlist,dir)
742                     with
743                         Not_found -> let res = 
744                           if dir then eval_formlist ~memo:false s Ptset.Int.empty formlist
745                           else eval_formlist ~memo:false Ptset.Int.empty s formlist 
746                         in (Hashtbl.add h_fold (hs,Formlist.hash formlist,dir) res;res)
747                   in(*
748                   let _ = pr "Evaluating on set (%s) with tree %s=%s" 
749                     (if dir then "left" else "right")
750                     (Tag.to_string (Tree.tag t))
751                     (Tree.dump_node t) ;
752                     StateSet.print fmt (Ptset.Int.elements s);
753                     pr ", formualae (with hash %i): \n" (Formlist.hash formlist);
754                     Formlist.pr fmt formlist;
755                     pr "result is ";
756                     StateSet.print fmt (Ptset.Int.elements r');
757                     pr " %b %b %b %b \n%!" rb rb1 rb2 mark ; 
758                   in *)
759                     if rb && ((dir&&rb1)|| ((not dir) && rb2))
760                     then 
761                       let acc = 
762                         let old_r = 
763                           try Configuration.IMap.find s conf.Configuration.results
764                           with Not_found -> RS.empty
765                         in
766                           Configuration.add acc r' (if mark then RS.cons t old_r else old_r)                    
767                       in
768                         loop sll fll acc
769                     else loop sll fll acc
770               | _ -> assert false
771           in
772             loop slist fl_list Configuration.empty
773
774         let h_trans = Hashtbl.create 4096
775
776         let get_up_trans slist ptag a tree =      
777           let key = (HASHINT2(hpl slist,Tag.hash ptag)) in
778             try
779           Hashtbl.find h_trans key              
780           with
781           | Not_found ->  
782               let f_list =
783                 Hashtbl.fold (fun q l acc ->
784                                 List.fold_left (fun fl_acc (ts,t)  ->
785                                                   if TagSet.mem ptag ts then Formlist.add t fl_acc
786                                                   else fl_acc)
787                                   
788                                   acc l)
789                   a.trans Formlist.empty
790               in
791               let res = fold_pl (fun _ _ acc -> f_list::acc) slist [] 
792               in
793                 (Hashtbl.add h_trans key res;res) 
794                   
795               
796         let h_tdconf = Hashtbl.create 511 
797         let rec bottom_up a tree conf next jump_fun root dotd init accu = 
798           if (not dotd) && (Configuration.is_empty conf ) then
799 (*                  let _ = pr "Returning early from %s, with accu %i, next is %s\n%!" 
800                     (Tree.dump_node tree) (Obj.magic accu) (Tree.dump_node next)
801                     in *)
802             accu,conf,next 
803           else
804 (*          let _ =   
805             pr "Going bottom up for tree with tag %s configuration is" 
806             (if Tree.is_nil tree then "###" else Tag.to_string (Tree.tag tree));
807             Configuration.pr fmt conf 
808             in *)
809             let below_right = Tree.is_below_right tree next in 
810               (*          let _ = Format.fprintf Format.err_formatter "below_right %s %s = %b\n%!"
811                           (Tree.dump_node tree) (Tree.dump_node next)  below_right
812                           in *)
813             let accu,rightconf,next_of_next =       
814             if below_right then (* jump to the next *)
815 (*            let _ = pr "Jumping to %s tag %s\n%!" (Tree.dump_node next) (Tag.to_string (Tree.tag next)) in   *)
816               bottom_up a next conf (jump_fun next) jump_fun (Tree.next_sibling tree) true init accu
817             else accu,Configuration.empty,next
818           in 
819 (*        let _ = if below_right then pr "Returning from jump to next = %s\n" (Tree.dump_node next)in   *)
820           let sub =
821             if dotd then
822               if below_right then (* only recurse on the left subtree *)
823 (*              let _ = pr "Topdown on left subtree\n%!" in      *)
824                 prepare_topdown a tree true
825               else 
826 (*              let _ = pr "Topdown on whole tree\n%!" in *)
827                 prepare_topdown a tree false
828             else conf
829           in
830           let conf,next =
831             (Configuration.merge rightconf sub, next_of_next)
832           in
833             if Tree.equal tree root then 
834 (*              let _ = pr "Stopping at root, configuration after topdown is:" ;
835                 Configuration.pr fmt conf;
836                 pr "\n%!"               
837               in *)  accu,conf,next 
838             else              
839           let parent = Tree.binary_parent tree in
840           let ptag = Tree.tag parent in
841           let dir = Tree.is_left tree in
842           let slist = Configuration.Ptss.fold (fun e a -> cons e a) conf.Configuration.sets Nil in
843           let fl_list = get_up_trans slist ptag a parent in
844           let slist = rev_pl (slist) in 
845 (*        let _ = pr "Current conf is : %s " (Tree.dump_node tree); 
846             Configuration.pr fmt conf;
847             pr "\n" 
848           in *)
849           let newconf = fold_f_conf parent slist fl_list conf dir in
850 (*        let _ = pr "New conf before pruning is (dir=%b):" dir;
851             Configuration.pr fmt newconf ;
852             pr "accu is %i\n" (RS.length accu);
853           in        *)
854           let accu,newconf = Configuration.IMap.fold (fun s res (ar,nc) ->
855                                                         if Ptset.Int.intersect s init then
856                                                           ( RS.concat res ar ,nc)
857                                                         else (ar,Configuration.add nc s res))
858             (newconf.Configuration.results) (accu,Configuration.empty) 
859           in
860 (*        let _ = pr "New conf after pruning is (dir=%b):" dir;
861             Configuration.pr fmt newconf ;
862             pr "accu is %i\n" (RS.length accu);
863           in        *)
864             bottom_up a parent newconf next jump_fun root false init accu
865
866         and prepare_topdown a t noright =
867           let tag = Tree.tag t in
868 (*        pr "Going top down on tree with tag %s = %s "  
869             (if Tree.is_nil t then "###" else (Tag.to_string(Tree.tag t))) (Tree.dump_node t); *)
870           let r = 
871             try
872               Hashtbl.find h_tdconf tag
873             with
874               | Not_found -> 
875                   let res = Hashtbl.fold (fun q l acc -> 
876                                             if List.exists (fun (ts,_) -> TagSet.mem tag ts) l
877                                             then Ptset.Int.add q acc
878                                             else acc) a.trans Ptset.Int.empty
879                   in Hashtbl.add h_tdconf tag res;res
880           in 
881 (*        let _ = pr ", among ";
882             StateSet.print fmt (Ptset.Int.elements r);
883             pr "\n%!";
884           in *)
885           let r = cons r Nil in
886           let set,res = top_down (~noright:noright) a t r t 1 in
887           let set = match set with
888             | Cons(x,_,Nil) ->x
889             | _ -> assert false 
890           in 
891 (*          pr "Result of topdown run is %!";
892             StateSet.print fmt (Ptset.Int.elements set);
893             pr ", number is %i\n%!" (RS.length res.(0));  *)
894             Configuration.add Configuration.empty set res.(0) 
895
896
897
898         let run_bottom_up a t k =
899           let trlist = Hashtbl.find a.trans (Ptset.Int.choose a.init)
900           in
901           let init = List.fold_left 
902             (fun acc (_,t) ->
903                let _,_,f,_ = Transition.node t in 
904                let _,_,l = fst ( Formula.st f ) in
905                  Ptset.Int.union acc l)
906             Ptset.Int.empty trlist
907           in
908           let tree1,jump_fun =
909             match k with
910               | `TAG (tag) -> 
911                   (*Tree.tagged_lowest t tag, fun tree -> Tree.tagged_next tree tag*)
912                   (Tree.tagged_desc tag t, fun tree -> Tree.tagged_foll_ctx tag tree t)
913               | `CONTAINS(_) -> (Tree.text_below t,fun tree -> Tree.text_next tree t)
914               | _ -> assert false
915           in
916           let tree2 = jump_fun tree1 in
917           let rec loop tree next acc = 
918 (*          let _ = pr "\n_________________________\nNew iteration\n" in 
919             let _ = pr "Jumping to %s\n%!" (Tree.dump_node tree) in  *)
920             let acc,conf,next_of_next = bottom_up a tree 
921               Configuration.empty next jump_fun (Tree.root tree) true init acc
922             in 
923               (*            let _ = pr "End of first iteration, conf is:\n%!";
924                             Configuration.pr fmt conf 
925                             in *)             
926             let acc = Configuration.IMap.fold 
927               ( fun s res acc -> if Ptset.Int.intersect init s
928                 then RS.concat res acc else acc) conf.Configuration.results acc
929             in
930               if Tree.is_nil next_of_next  (*|| Tree.equal next next_of_next *)then
931                 acc
932               else loop next_of_next (jump_fun next_of_next) acc
933           in
934           loop tree1 tree2 RS.empty
935
936
937     end
938           
939     let top_down_count a t = let module RI = Run(Integer) in Integer.length (RI.run_top_down a t)
940     let top_down a t = let module RI = Run(IdSet) in (RI.run_top_down a t)
941     let bottom_up_count a t k = let module RI = Run(Integer) in Integer.length (RI.run_bottom_up a t k)
942
943