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