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