.
[SXSI/xpathcomp.git] / ata.ml
1 INCLUDE "debug.ml"
2 INCLUDE "utils.ml"
3 open Camlp4.Struct
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
38     type 'hcons node = {
39       pos : 'hcons expr;
40       mutable neg : 'hcons;
41       st : (StateSet.t*StateSet.t*StateSet.t)*(StateSet.t*StateSet.t*StateSet.t);
42       size: int; (* Todo check if this is needed *)
43     }
44         
45     external hash_const_variant : [> ] -> int = "%identity" 
46     module rec Node : Hcons.S with type data = Data.t = Hcons.Make (Data)
47     and Data : Hashtbl.HashedType  with type t = Node.t node =
48     struct 
49     type t =  Node.t node
50     let equal x y = x.size == y.size &&
51       match x.pos,y.pos with
52         | a,b when a == b -> true
53         | Or(xf1,xf2),Or(yf1,yf2) 
54         | And(xf1,xf2),And(yf1,yf2)  -> (xf1 == yf1) && (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,Uid.to_int f1.Node.id, Uid.to_int f2.Node.id)
62         | And (f1,f2) -> HASHINT3(PRIME3,Uid.to_int f1.Node.id, Uid.to_int f2.Node.id)
63         | Atom(d,p,s) -> HASHINT4(PRIME4,hash_const_variant d,vb p,s)       
64     end
65
66     type t = Node.t
67     let hash x = x.Node.key
68     let uid x = x.Node.id
69     let equal = Node.equal 
70     let expr f = f.Node.node.pos 
71     let st f = f.Node.node.st
72     let size f = f.Node.node.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 = Node.make { pos = neg; neg = (Obj.magic 0); st = s2; size = size2 } in
112       let pnode = Node.make { pos = pos; neg = nnode ; st = s1; size = size1 }
113       in 
114         (Node.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 = f.Node.node.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*TagSet.t*bool*Formula.t*bool
198   include Hcons.Make(struct
199                        type t = node
200                        let hash (s,ts,m,f,b) = HASHINT5(s,Uid.to_int (TagSet.uid ts),
201                                                         Uid.to_int (Formula.uid f),
202                                                         vb m,vb b)
203                        let equal (s,ts,b,f,m) (s',ts',b',f',m') = 
204                          s == s' && ts == ts' && b==b' && m==m' && f == f'
205                      end)
206     
207   let print ppf f = let (st,ts,mark,form,b) = node f in
208     Format.fprintf ppf "(%i, " st;
209     TagSet.print ppf ts;
210     Format.fprintf ppf ") %s" (if mark then "⇒" else "→");
211     Formula.print ppf form;
212     Format.fprintf ppf "%s%!" (if b then " (b)" else "")
213
214
215   module Infix = struct
216   let ( ?< ) x = x
217   let ( >< ) state (l,mark) = state,(l,mark,false)
218   let ( ><@ ) state (l,mark) = state,(l,mark,true)
219   let ( >=> ) (state,(label,mark,bur)) form = (state,label,(make (state,label,mark,form,bur)))
220   end
221
222 end
223
224 module TransTable = Hashtbl
225  
226 module Formlist = struct 
227   include Hlist.Make(Transition)
228   let print ppf fl = 
229     iter (fun t -> Transition.print ppf t; Format.pp_print_newline ppf ()) fl
230 end
231
232 module Formlistlist = 
233 struct
234   include Hlist.Make(Formlist)
235   let print ppf fll =
236     iter (fun fl -> Formlist.print ppf fl; Format.pp_print_newline ppf ())fll
237 end
238   
239 type 'a t = { 
240     id : int;
241     mutable states : Ptset.Int.t;
242     init : Ptset.Int.t;
243     starstate : Ptset.Int.t option;
244     (* Transitions of the Alternating automaton *)
245     trans : (State.t,(TagSet.t*Transition.t) list) Hashtbl.t;
246     query_string: string;
247  }
248
249         
250 let dump ppf a = 
251   Format.fprintf ppf "Automaton (%i) :\n" a.id;
252   Format.fprintf ppf "States : "; StateSet.print ppf a.states;
253   Format.fprintf ppf "\nInitial states : "; StateSet.print ppf a.init;
254   Format.fprintf ppf "\nAlternating transitions :\n";
255   let l = Hashtbl.fold (fun k t acc -> 
256                           (List.map (fun (ts,tr) -> (ts,k),Transition.node tr) t) @ acc) a.trans [] in
257   let l = List.sort (fun ((tsx,x),_) ((tsy,y),_) -> 
258                        if y-x == 0 then TagSet.compare tsy tsx else y-x) l in
259   let maxh,maxt,l_print = 
260     List.fold_left (
261       fun (maxh,maxt,l) ((ts,q),(_,_,b,f,_)) ->                   
262         let s = 
263           if TagSet.is_finite ts 
264           then "{" ^ (TagSet.fold (fun t a -> a ^ " '" ^ (Tag.to_string t)^"'") ts "") ^" }"
265           else let cts = TagSet.neg ts in
266           if TagSet.is_empty cts then "*" else
267           (TagSet.fold (fun t a -> a ^ " " ^ (Tag.to_string t)) cts "*\\{"
268           )^ "}"
269         in
270         let s = Printf.sprintf "(%s,%i)" s q in
271         let s_frm =
272           Formula.print Format.str_formatter f;
273           Format.flush_str_formatter()     
274         in
275           (max (String.length s) maxh, max (String.length s_frm) maxt,
276            (s,(if b then "⇒" else "→"),s_frm)::l)) (0,0,[]) l
277   in
278     Format.fprintf ppf "%s\n%!" (String.make (maxt+maxh+3) '_');
279     List.iter (fun (s,m,f) -> let s = s ^ (String.make (maxh-(String.length s)) ' ') in
280                  Format.fprintf ppf "%s %s %s\n" s m f) l_print;
281     Format.fprintf ppf "%s\n%!" (String.make (maxt+maxh+3) '_')
282     
283
284 module FormTable = Hashtbl.Make(struct
285                                   type t = Formula.t*StateSet.t*StateSet.t
286                                   let equal (f1,s1,t1) (f2,s2,t2) =
287                                     f1 == f2 && s1 == s2 && t1 == t2
288                                   let hash (f,s,t) = 
289                                     HASHINT3(Uid.to_int (Formula.uid f),
290                                              Uid.to_int (StateSet.uid s),
291                                              Uid.to_int (StateSet.uid t))
292                                 end)
293 module F = Formula
294
295 let eval_form_bool = 
296   let h_f = FormTable.create BIG_H_SIZE in
297     fun f s1 s2 ->
298       let rec loop f =
299         match F.expr f with
300           | F.True -> true,true,true
301           | F.False -> false,false,false
302           | F.Atom((`Left|`LLeft),b,q) ->
303               if b == (StateSet.mem q s1) 
304               then (true,true,false) 
305               else false,false,false
306           | F.Atom(_,b,q) -> 
307               if b == (StateSet.mem q s2) 
308               then (true,false,true)
309               else false,false,false    
310           | f' -> 
311               try FormTable.find h_f (f,s1,s2)
312               with Not_found -> let r =
313                 match f' with
314                   | F.Or(f1,f2) ->          
315                       let b1,rl1,rr1 = loop f1
316                       in
317                         if b1 && rl1 && rr1 then (true,true,true)  else
318                           let b2,rl2,rr2 = loop f2  in
319                           let rl1,rr1 = if b1 then rl1,rr1 else false,false
320                           and rl2,rr2 = if b2 then rl2,rr2 else false,false
321                           in (b1 || b2, rl1||rl2,rr1||rr2)
322                                
323                   | F.And(f1,f2) -> 
324                       let b1,rl1,rr1 = loop f1 in
325                         if b1 && rl1 && rr1 then (true,true,true) else
326                           if b1 then 
327                             let b2,rl2,rr2 = loop f2 in
328                               if b2 then (true,rl1||rl2,rr1||rr2) else (false,false,false)
329                           else (false,false,false)
330                   | _ -> assert false
331               in FormTable.add h_f (f,s1,s2) r;r
332       in loop f
333
334            
335 module FTable = Hashtbl.Make(struct
336                                type t = Tag.t*Formlist.t*StateSet.t*StateSet.t
337                                let equal (tg1,f1,s1,t1) (tg2,f2,s2,t2) =
338                                  tg1 == tg2 && f1 == f2 &&  s1 == s2 && t1 == t2;;
339                                let hash (tg,f,s,t) =  
340                                  HASHINT4(tg, Uid.to_int (Formlist.uid f),
341                                           Uid.to_int (StateSet.uid s),
342                                           Uid.to_int (StateSet.uid t))
343                              end)
344
345
346 let h_f = FTable.create BIG_H_SIZE 
347 type merge_conf = NO | ONLY1 | ONLY2 | ONLY12 | MARK | MARK1 | MARK2 | MARK12
348 (* 000 001 010 011 100 101 110 111 *)
349 let eval_formlist tag s1 s2 fl =
350   let rec loop fl =
351           try 
352             FTable.find h_f (tag,fl,s1,s2)
353           with 
354             | Not_found  -> 
355                 match Formlist.node fl with
356                   | Formlist.Cons(f,fll) ->
357                       let q,ts,mark,f,_ = Transition.node f in
358                       let b,b1,b2 = 
359                         if TagSet.mem tag ts then eval_form_bool f s1 s2 else (false,false,false)
360                       in
361                       let (s,(b',b1',b2',amark)) as res = loop fll in
362                       let r = if b then (StateSet.add q s, (b, b1'||b1,b2'||b2,mark||amark))
363                       else res
364                       in FTable.add h_f (tag,fl,s1,s2) r;r
365                   | Formlist.Nil -> StateSet.empty,(false,false,false,false)
366   in 
367   let r,conf = loop fl
368   in
369   r,(match  conf with
370     | (false,_,_,_) -> NO
371     | (_,false,false,false) -> NO
372     | (_,true,false,false) -> ONLY1
373     | (_,false,true,false) -> ONLY2
374     | (_,true,true,false) -> ONLY12
375     | (_,false,false,true) -> MARK
376     | (_,true,false,true) -> MARK1
377     | (_,false,true,true) -> MARK2
378     | _ -> MARK12)
379
380 let bool_of_merge conf =
381   match  conf with
382     | NO -> false,false,false,false
383     | ONLY1 -> true,true,false,false
384     | ONLY2 -> true,false,true,false 
385     | ONLY12 -> true,true,true,false 
386     | MARK -> true,false,false,true
387     | MARK1 -> true,true,false,true
388     | MARK2 -> true,false,true,true
389     | MARK12 -> true,true,true,true
390
391
392 let tags_of_state a q = 
393   Hashtbl.fold  
394     (fun p l acc -> 
395        if p == q then List.fold_left 
396          (fun acc (ts,t) -> 
397             let _,_,_,_,aux = Transition.node t in
398               if aux then acc else
399                 TagSet.cup ts acc) acc l
400          
401        else acc) a.trans TagSet.empty
402       
403       
404
405     let tags a qs = 
406       let ts = Ptset.Int.fold (fun q acc -> TagSet.cup acc (tags_of_state a q)) qs TagSet.empty
407       in
408         if TagSet.is_finite ts 
409         then `Positive(TagSet.positive ts)
410         else `Negative(TagSet.negative ts)
411         
412     let inter_text a b =
413       match b with
414         | `Positive s -> let r = Ptset.Int.inter a s in (r,Ptset.Int.mem Tag.pcdata r, true)
415         | `Negative s -> let r = Ptset.Int.diff a s in (r, Ptset.Int.mem Tag.pcdata r, false)
416       
417
418     module type ResultSet = 
419     sig
420       type t
421       type elt = [` Tree ] Tree.node
422       val empty : t
423       val cons : elt -> t -> t
424       val concat : t -> t -> t
425       val iter : ( elt -> unit) -> t -> unit
426       val fold : ( elt -> 'a -> 'a) -> t -> 'a -> 'a
427       val map : ( elt -> elt) -> t -> t
428       val length : t -> int
429       val merge : merge_conf -> elt -> t -> t -> t 
430       val mk_quick_tag_loop : (elt -> elt -> 'a*t array) -> 'a -> int -> Tree.t -> Tag.t -> (elt -> elt -> 'a*t array)
431       val mk_quick_star_loop : (elt -> elt -> 'a*t array) -> 'a -> int -> Tree.t -> (elt -> elt -> 'a*t array)
432     end
433
434     module Integer : ResultSet =
435     struct
436       type t = int
437       type elt = [`Tree] Tree.node
438
439       let empty = 0
440       let cons _ x = x+1
441       let concat x y = x + y
442       let iter _ _ = failwith "iter not implemented"
443       let fold _ _ _ = failwith "fold not implemented"
444       let map _ _ = failwith "map not implemented"
445       let length x = x
446       let merge2 conf t res1 res2 = 
447         let rb,rb1,rb2,mark = conf in
448         if rb then
449           let res1 = if rb1 then res1 else 0
450           and res2 = if rb2 then res2 else 0
451           in
452             if mark then 1+res1+res2
453             else res1+res2
454         else 0
455       let merge conf t res1 res2 = 
456         match conf with
457             NO -> 0                         
458           | MARK -> 1
459           | MARK1 -> res1+1         
460           | ONLY1 -> res1                
461           | ONLY2 -> res2           
462           | ONLY12 -> res1+res2     
463           | MARK2 -> res2+1         
464           | MARK12 -> res1+res2+1   
465
466       let mk_quick_tag_loop _ sl ss tree tag = ();
467         fun t ctx ->
468           (sl, Array.make ss (Tree.subtree_tags tree tag t))
469       let mk_quick_star_loop _ sl ss tree = ();
470         fun t ctx -> 
471           (sl, Array.make ss (Tree.subtree_elements tree t))
472           
473     end
474
475     module IdSet : ResultSet= 
476     struct
477       type elt = [`Tree] Tree.node
478       type node = Nil 
479                   | Cons of elt * node 
480                   | Concat of node*node
481    
482       and t = { node : node;
483                 length :  int }
484
485       let empty = { node = Nil; length = 0 }
486         
487       let cons e t = { node = Cons(e,t.node); length = t.length+1 }
488       let concat t1 t2 = { node = Concat(t1.node,t2.node); length = t1.length+t2.length }
489       let append e t = { node = Concat(t.node,Cons(e,Nil)); length = t.length+1 } 
490         
491       let fold f l acc = 
492         let rec loop acc t = match t with
493           | Nil -> acc
494           | Cons (e,t) -> loop (f e acc) t
495           | Concat (t1,t2) -> loop (loop acc t1) t2
496         in
497           loop acc l.node
498             
499       let length l = l.length
500         
501         
502       let iter f l =
503         let rec loop = function
504           | Nil -> ()
505           | Cons (e,t) -> f e; loop t
506           | Concat(t1,t2) -> loop t1;loop t2
507         in loop l.node
508
509       let map f l =
510         let rec loop = function 
511           | Nil -> Nil
512           | Cons(e,t) -> Cons(f e, loop t)
513           | Concat(t1,t2) -> Concat(loop t1,loop t2)
514         in
515           { l with node = loop l.node }
516             
517       let merge conf t res1 res2 = 
518         match conf with
519            NO -> empty
520           | MARK -> cons t empty
521           | ONLY1 -> res1
522           | ONLY2 -> res2
523           | ONLY12 -> { node = (Concat(res1.node,res2.node));
524                         length = res1.length + res2.length ;}
525           | MARK12 -> { node = Cons(t,(Concat(res1.node,res2.node)));
526                         length = res1.length + res2.length + 1;}
527           | MARK1 -> { node = Cons(t,res1.node);
528                         length = res1.length + 1;}
529           | MARK2 -> { node = Cons(t,res2.node);
530                        length = res2.length + 1;}
531
532       let mk_quick_tag_loop f _ _ _ _ = f
533       let mk_quick_star_loop f _ _ _ = f
534     end
535     module GResult(Doc : sig val doc : Tree.t end) = struct
536       type bits
537       type elt = [` Tree] Tree.node
538       external create_empty : int -> bits = "caml_result_set_create" "noalloc"
539       external set : bits -> int -> unit = "caml_result_set_set" "noalloc"
540       external next : bits -> int -> int = "caml_result_set_next" "noalloc"
541       external count : bits -> int  = "caml_result_set_count" "noalloc"
542       external clear : bits -> elt -> elt -> unit = "caml_result_set_clear" "noalloc"
543          
544       external set_tag_bits : bits -> Tag.t -> Tree.t -> elt -> elt = "caml_set_tag_bits" "noalloc"
545       type t = 
546          { segments : elt list;
547            bits : bits;
548          }
549
550       let ebits = 
551         let size = (Tree.subtree_size Doc.doc Tree.root) in
552         create_empty (size*2+1)
553
554       let empty = { segments = [];
555                     bits = ebits }
556         
557       let cons e t = 
558         let rec loop l = match l with
559           | [] -> { bits = (set t.bits (Obj.magic e);t.bits);
560                     segments = [ e ] }
561           | p::r -> 
562               if Tree.is_binary_ancestor Doc.doc e p then
563               loop r
564               else
565               { bits = (set t.bits (Obj.magic e);t.bits);
566                 segments = e::l }
567         in
568         loop t.segments
569                     
570       let concat t1 t2 =
571         if t2.segments == [] then t1
572         else
573         if t1.segments == [] then t2
574         else
575         let h2 = List.hd t2.segments in
576         let rec loop l = match l with
577           | [] -> t2.segments
578           | p::r -> 
579               if Tree.is_binary_ancestor Doc.doc p h2 then
580               l
581               else
582               p::(loop r)
583         in
584         { bits = t1.bits;
585           segments = loop t1.segments 
586         }
587
588       let iter f t =
589         let rec loop i = 
590           if i == -1 then ()
591           else (f ((Obj.magic i):elt);loop (next t.bits i))
592         in loop (next t.bits 0)
593           
594       let fold f t acc = 
595         let rec loop i acc = 
596           if i == -1 then acc
597           else loop (next t.bits i) (f ((Obj.magic i):elt) acc)
598         in loop (next t.bits 0) acc
599
600       let map _ _ = failwith "noop"
601       (*let length t = let cpt = ref 0 in
602       iter (fun _ -> incr cpt) t; !cpt *)
603       let length t = count t.bits 
604       
605       let clear_bits t = 
606         let rec loop l = match l with
607            [] -> ()
608           | idx::ll ->
609               clear t.bits idx (Tree.closing Doc.doc idx); loop ll
610         in
611         loop t.segments;empty
612
613       let merge (rb,rb1,rb2,mark) elt t1 t2 =
614         if rb then
615 (*      let _ = Printf.eprintf "Lenght before merging is %i %i\n"
616           (List.length t1.segments) (List.length t2.segments)
617         in *)
618         match t1.segments,t2.segments with
619            [],[] -> if mark then cons elt empty else empty
620           | [_],[] when rb1 -> if mark then cons elt t1 else t1
621           | [], [_] when rb2 -> if mark then cons elt t2 else t2
622           | [_],[_] when rb1 && rb2 -> if mark then cons elt empty else
623             concat t1 t2
624           | _ -> 
625         let t1 = if rb1 then t1 else clear_bits t1
626         and t2 = if rb2 then t2 else clear_bits t2
627         in
628         (if mark then cons elt (concat t1 t2)
629          else concat t1 t2)
630         else
631         let _ = clear_bits t1 in
632         clear_bits t2
633
634       let merge conf t t1 t2 = 
635         match t1.segments,t2.segments,conf with
636           | _,_,NO -> let _ = clear_bits t1 in clear_bits t2
637           | [],[],(MARK1|MARK2|MARK12|MARK) -> cons t empty
638           | [],[],_ -> empty
639           | [_],[],(ONLY1|ONLY12) -> t1
640           | [_],[],(MARK1|MARK12) -> cons t t1
641           | [],[_],(ONLY2|ONLY12) -> t2
642           | [],[_],(MARK2|MARK12) -> cons t t2
643           | [_],[_],ONLY12 -> concat t1 t2
644           | [_],[_],MARK12 -> cons t empty
645           | _,_,MARK -> let _ = clear_bits t2 in cons t (clear_bits t1)     
646           | _,_,ONLY1 -> let _ = clear_bits t2 in t1
647           | _,_,ONLY2 -> let _ = clear_bits t1 in t2
648           | _,_,ONLY12 -> concat t1 t2
649           | _,_,MARK1 -> let _ = clear_bits t2 in cons t t1
650           | _,_,MARK2 -> let _ = clear_bits t1 in cons t t2
651           | _,_,MARK12 ->  cons t (concat t1 t2)
652
653       let mk_quick_tag_loop _ sl ss tree tag = ();
654         fun t _ ->        
655           let res = empty in
656           let first = set_tag_bits empty.bits tag tree t in
657           let res = 
658             if first == Tree.nil then res else 
659             cons first res 
660           in
661           (sl, Array.make ss res)
662
663       let mk_quick_star_loop f _ _ _ = f
664     end
665     module Run (RS : ResultSet) =
666     struct
667
668       module SList = Hlist.Make (StateSet)
669
670
671
672 IFDEF DEBUG
673 THEN
674       module IntSet = Set.Make(struct type t = int let compare = (-) end)
675 INCLUDE "html_trace.ml"
676               
677 END             
678       let mk_fun f s = D_IGNORE_(register_funname f s,f)
679       let mk_app_fun f arg s = let g = f arg in 
680         D_IGNORE_(register_funname g ((get_funname f) ^ " " ^ s), g) 
681       let mk_app_fun2 f arg1 arg2 s = let g = f arg1 arg2 in 
682         D_IGNORE_(register_funname g ((get_funname f) ^ " " ^ s), g) 
683
684       let string_of_ts tags = (Ptset.Int.fold (fun t a -> a ^ " " ^ (Tag.to_string t) ) tags "{")^ " }"
685
686
687       module Algebra =
688         struct
689           type jump = [ `NIL | `ANY |`ANYNOTEXT | `JUMP ]
690           type t = jump*Ptset.Int.t*Ptset.Int.t
691           let jts = function 
692           | `JUMP -> "JUMP"
693           | `NIL -> "NIL"
694           | `ANY -> "ANY"
695           | `ANYNOTEXT -> "ANYNOTEXT"
696           let merge_jump (j1,c1,l1) (j2,c2,l2) = 
697             match j1,j2 with
698               | _,`NIL -> (j1,c1,l1)
699               | `NIL,_ -> (j2,c2,l2)
700               | `ANY,_ -> (`ANY,Ptset.Int.empty,Ptset.Int.empty)
701               | _,`ANY -> (`ANY,Ptset.Int.empty,Ptset.Int.empty)
702               | `ANYNOTEXT,_ -> 
703                   if Ptset.Int.mem Tag.pcdata (Ptset.Int.union c2 l2) then
704                   (`ANY,Ptset.Int.empty,Ptset.Int.empty)
705                   else
706                   (`ANYNOTEXT,Ptset.Int.empty,Ptset.Int.empty)
707               | _,`ANYNOTEXT -> 
708                   if Ptset.Int.mem Tag.pcdata (Ptset.Int.union c1 l1) then
709                   (`ANY,Ptset.Int.empty,Ptset.Int.empty)
710                   else
711                   (`ANYNOTEXT,Ptset.Int.empty,Ptset.Int.empty)
712               | `JUMP,`JUMP -> (`JUMP, Ptset.Int.union c1 c2,Ptset.Int.union l1 l2)
713
714           let merge_jump_list = function 
715             | [] -> `NIL,Ptset.Int.empty,Ptset.Int.empty
716             | p::r -> 
717                 List.fold_left (merge_jump) p r
718               
719           let labels a s = 
720             Hashtbl.fold 
721             (
722               fun q l acc -> 
723                 if (q == s)
724                 then 
725
726                   (List.fold_left 
727                       (fun acc (ts,f) ->
728                         let _,_,_,_,bur = Transition.node f in
729                         if bur then acc else TagSet.cup acc ts) 
730                     acc l)
731                 else acc ) a.trans TagSet.empty
732           exception Found
733             
734           let is_rec a s access = 
735             List.exists
736               (fun (_,t) -> let _,_,_,f,_ = Transition.node t in
737               StateSet.mem s ((fun (_,_,x) -> x) (access (Formula.st f)))) (Hashtbl.find a.trans s) 
738                      
739           let is_final_marking a s =
740             List.exists (fun (_,t) -> let _,_,m,f,_ = Transition.node t in m&& (Formula.is_true f))
741               (Hashtbl.find a.trans s)
742               
743               
744           let decide a c_label l_label dir_states dir =
745                         
746             let l = StateSet.fold 
747               (fun s l -> 
748                  let s_rec = is_rec a s (if dir then fst else snd) in
749                  let s_rec = if dir then s_rec else
750                  (* right move *)
751                  is_rec a s fst
752                  in
753                  let s_lab = labels a s in
754                  let jmp,cc,ll = 
755                    if (not (TagSet.is_finite s_lab)) then
756                    if TagSet.mem Tag.pcdata s_lab then  (`ANY,Ptset.Int.empty,Ptset.Int.empty)
757                    else (`ANYNOTEXT,Ptset.Int.empty,Ptset.Int.empty)
758                    else 
759                    if s_rec 
760                    then (`JUMP,Ptset.Int.empty, TagSet.positive 
761                            (TagSet.cap (TagSet.inj_positive l_label) s_lab))
762                    else (`JUMP,TagSet.positive 
763                            (TagSet.cap (TagSet.inj_positive c_label) s_lab),
764                          Ptset.Int.empty )
765                  in
766                    (if jmp != `ANY 
767                     && jmp != `ANYNOTEXT 
768                     && Ptset.Int.is_empty cc 
769                     && Ptset.Int.is_empty ll
770                     then (`NIL,Ptset.Int.empty,Ptset.Int.empty)
771                     else  (jmp,cc,ll))::l) dir_states []
772             in merge_jump_list l                            
773             
774               
775         end 
776
777
778
779       let choose_jump (d,cl,ll) f_nil f_t1 f_s1 f_tn f_sn f_s1n f_notext f_maytext =
780         match d with
781           | `NIL -> (`NIL,f_nil)
782           | `ANYNOTEXT -> `ANY,f_notext
783           | `ANY -> `ANY,f_maytext
784           | `JUMP -> 
785               if Ptset.Int.is_empty cl then
786               if Ptset.Int.is_singleton ll then
787               let tag = Ptset.Int.choose ll in 
788               (`TAG(tag),mk_app_fun f_tn tag (Tag.to_string tag))
789               else
790               (`MANY(ll),mk_app_fun f_sn ll (string_of_ts ll))
791               else if Ptset.Int.is_empty ll then
792               if Ptset.Int.is_singleton cl then
793               let tag = Ptset.Int.choose cl in 
794               (`TAG(tag),mk_app_fun f_t1 tag (Tag.to_string tag))
795               else
796               (`MANY(cl),mk_app_fun f_s1 cl (string_of_ts cl))
797               else
798               (`ANY,mk_app_fun2 f_s1n cl ll ((string_of_ts cl) ^ " " ^ (string_of_ts ll)))
799
800           | _ -> assert false
801           
802       let choose_jump_down tree d =
803         choose_jump d
804           (mk_fun (fun _ -> Tree.nil) "Tree.mk_nil")
805           (mk_fun (Tree.tagged_child tree) "Tree.tagged_child") 
806           (mk_fun (Tree.select_child tree) "Tree.select_child")
807           (mk_fun (Tree.tagged_descendant tree) "Tree.tagged_desc")
808           (mk_fun (Tree.select_descendant tree) "Tree.select_desc") 
809           (mk_fun (fun _ _ -> Tree.first_child tree) "[FIRSTCHILD]Tree.select_child_desc")
810           (mk_fun (Tree.first_element tree) "Tree.first_element")
811           (mk_fun (Tree.first_child tree) "Tree.first_child") 
812
813       let choose_jump_next tree d = 
814         choose_jump d
815           (mk_fun (fun _ _ -> Tree.nil) "Tree.mk_nil2")
816           (mk_fun (Tree.tagged_following_sibling_below tree) "Tree.tagged_sibling_ctx")
817           (mk_fun (Tree.select_following_sibling_below tree) "Tree.select_sibling_ctx")
818           (mk_fun (Tree.tagged_following_below tree) "Tree.tagged_foll_ctx")
819           (mk_fun (Tree.select_following_below tree) "Tree.select_foll_ctx")
820           (mk_fun (fun _ _ -> Tree.next_sibling_below tree) "[NEXTSIBLING]Tree.select_sibling_foll_ctx")
821           (mk_fun (Tree.next_element_below tree) "Tree.next_element_ctx")         
822           (mk_fun (Tree.next_sibling_below tree) "Tree.node_sibling_ctx")         
823                           
824           
825       module SListTable = Hashtbl.Make(struct type t = SList.t
826                                               let equal = (==)
827                                               let hash t = Uid.to_int t.SList.Node.id
828                                        end)
829
830
831       module TransCache =
832       struct
833         type cell = { key : int;
834                       obj : Obj.t }
835         type 'a t = cell array
836         let dummy = { key = 0; obj = Obj.repr () }
837         let create n = Array.create 25000 dummy
838         let hash a b = HASHINT2(Obj.magic a, Uid.to_int b.SList.Node.id)
839
840         let find_slot t key =
841           let rec loop i =
842             if (t.(i)  != dummy) && (t.(i).key != key)
843             then loop ((i+1 mod 25000))
844             else i
845           in loop (key mod 25000)
846         ;;
847
848         let find t k1 k2 = 
849           let i = find_slot t (hash k1 k2) in
850           if t.(i) == dummy then raise Not_found
851           else Obj.magic (t.(i).obj)
852             
853         let add t k1 k2 v = 
854           let key = hash k1 k2 in
855           let i = find_slot t key in
856           t.(i)<- { key = key; obj = (Obj.repr v) }
857
858       end
859
860       module TransCache2 = 
861       struct
862         type 'a t = Obj.t array SListTable.t
863         let create n = SListTable.create n
864         let dummy = Obj.repr (fun _ -> assert false)
865         let find (h :'a t) tag slist : 'a =
866           let tab = 
867             try
868               SListTable.find h slist
869             with
870                Not_found -> 
871                  SListTable.add h slist (Array.create 10000 dummy);
872                  raise Not_found
873           in
874           let res = tab.(tag) in
875           if res == dummy then raise Not_found else (Obj.magic res)
876
877         let add (h : 'a t) tag slist (data : 'a) =
878           let tab = 
879             try
880               SListTable.find h slist
881             with
882                Not_found -> 
883                  let arr = Array.create 10000 dummy in
884                  SListTable.add h slist arr;
885                  arr
886           in
887           tab.(tag) <- (Obj.repr data)
888           
889
890       end
891
892       module TransCache = 
893       struct 
894         external get : 'a array -> int ->'a = "%array_unsafe_get"
895         external set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
896         type fun_tree = [`Tree] Tree.node -> [`Tree] Tree.node -> SList.t*RS.t array
897         type t = fun_tree array array
898         let dummy_cell = [||] 
899         let create n = Array.create n dummy_cell
900         let dummy = fun _ _-> assert false
901         let find h tag slist =
902           let tab = get h (Uid.to_int slist.SList.Node.id) in
903           if tab == dummy_cell then raise Not_found
904           else
905           let res = get tab tag in
906           if res == dummy then raise Not_found else res
907
908         let add (h : t) tag slist (data : fun_tree) =
909           let tab = get h (Uid.to_int slist.SList.Node.id) in
910           let tab = if tab == dummy_cell then
911             let x = Array.create 100000 dummy in
912             (set h (Uid.to_int slist.SList.Node.id) x;x)
913           else tab
914           in
915           set tab tag data        
916       end
917         
918         
919       let td_trans = TransCache.create 100000 (* should be number of tags *number of states^2
920                                                 in the document *)
921
922       let empty_size n =
923         let rec loop acc = function 0 -> acc
924           | n -> loop (SList.cons StateSet.empty acc) (n-1)
925         in loop SList.nil n
926              
927       module FllTable = Hashtbl.Make (struct type t = Formlistlist.t
928                                              let equal = (==)
929                                              let hash t = Uid.to_int t.Formlistlist.Node.id
930                                       end)
931         
932       module Fold2Res = struct
933         external get : 'a array -> int ->'a = "%array_unsafe_get"
934         external set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
935         external field1 : 'a -> 'b = "%field1"
936         type 'a t = 'a array array array array
937         let dummy = [||]
938         let dummy_val : 'a =
939           let v = Obj.repr ((),2,()) in
940           Obj.magic v
941
942
943         let create n = Array.create n dummy
944         let find h tag fl s1 s2 = 
945           let af = get h tag in
946           if af == dummy then raise Not_found
947           else 
948           let as1 = get af (Uid.to_int fl.Formlistlist.Node.id) in
949           if as1 == dummy then raise Not_found
950           else 
951           let as2 = get as1 (Uid.to_int s1.SList.Node.id) in
952           if as2 == dummy then raise Not_found
953           else 
954           let v = get as2 (Uid.to_int s2.SList.Node.id) in
955           if field1 v == 2 then raise Not_found
956           else 
957           v
958
959         
960         let add h tag fl s1 s2 data = 
961           let af =
962             let x = get h tag in
963             if x == dummy then 
964             begin
965               let y = Array.make 100000 dummy in
966               set h tag y;y
967             end
968             else x
969           in
970           let as1 = 
971             let x = get af (Uid.to_int fl.Formlistlist.Node.id) in 
972             if x == dummy then
973             begin
974               let y = Array.make 100000 dummy in
975               set af (Uid.to_int fl.Formlistlist.Node.id) y;y
976             end
977             else x
978           in
979           let as2 = 
980             let x = get as1 (Uid.to_int s1.SList.Node.id) in 
981             if x == dummy then 
982             begin
983               let y = Array.make 100000 dummy_val in
984               set as1 (Uid.to_int s1.SList.Node.id) y;y
985             end
986             else x
987           in
988           set as2 (Uid.to_int s2.SList.Node.id) data    
989       end
990
991
992
993
994         
995       module Fold2Res2 = struct
996         include Hashtbl.Make(struct 
997                                type t = Tag.t*Formlistlist.t*SList.t*SList.t
998                                let equal (a,b,c,d) (x,y,z,t) =
999                                  a == x && b == y && c == z && d == t
1000                                let hash (a,b,c,d) = HASHINT4 (a,
1001                                                               Uid.to_int b.Formlistlist.Node.id,
1002                                                               Uid.to_int c.SList.Node.id,
1003                                                               Uid.to_int d.SList.Node.id)
1004                              end)
1005         let add h t f s1 s2 d =
1006           add h (t,f,s1,s2) d
1007         let find h t f s1 s2 =
1008           find h (t,f,s1,s2)
1009       end
1010
1011       module Fold2ResOld =
1012       struct
1013         type cell = { key : int;
1014                       obj : Obj.t }
1015         type 'a t = cell array
1016         let dummy = { key = 0; obj = Obj.repr () }
1017         let create n = Array.create 25000 dummy
1018         let hash a b c d = HASHINT4(Obj.magic a, 
1019                                     Uid.to_int b.Formlistlist.Node.id, 
1020                                     Uid.to_int c.SList.Node.id,
1021                                     Uid.to_int d.SList.Node.id)
1022
1023         let find_slot t key =
1024           let rec loop i =
1025             if (t.(i)  != dummy) && (t.(i).key != key)
1026             then loop ((i+1 mod 25000))
1027             else i
1028           in loop (key mod 25000)
1029         ;;
1030
1031         let find t k1 k2 k3 k4 = 
1032           let i = find_slot t (hash k1 k2 k3 k4) in
1033           if t.(i) == dummy then raise Not_found
1034           else Obj.magic (t.(i).obj)
1035             
1036         let add t k1 k2 k3 k4 v = 
1037           let key = hash k1 k2 k3 k4 in
1038           let i = find_slot t key in
1039           t.(i)<- { key = key; obj = (Obj.repr v) }
1040
1041       end
1042
1043       let h_fold2 = Fold2Res.create 10000
1044       
1045       let top_down ?(noright=false) a tree t slist ctx slot_size =      
1046         let pempty = empty_size slot_size in    
1047         let rempty = Array.make slot_size RS.empty in
1048         (* evaluation starts from the right so we put sl1,res1 at the end *)
1049         let eval_fold2_slist fll t tag (sl2,res2) (sl1,res1) =
1050           let res = Array.copy rempty in
1051            try
1052              let r,b,btab = Fold2Res.find h_fold2 tag fll sl1 sl2  in
1053              if b then for i=0 to slot_size - 1 do
1054              res.(i) <- RS.merge btab.(i) t res1.(i) res2.(i);
1055              done;
1056              r,res
1057              with
1058              Not_found -> 
1059                begin 
1060                  let btab = Array.make slot_size NO in      
1061                  let rec fold l1 l2 fll i aq ab = 
1062                    match fll.Formlistlist.Node.node,
1063                      l1.SList.Node.node,
1064                      l2.SList.Node.node
1065                    with      
1066                      | Formlistlist.Cons(fl,fll),
1067                       SList.Cons(s1,ll1),
1068                       SList.Cons(s2,ll2) ->
1069                          let r',conf = eval_formlist tag s1 s2 fl in
1070                          let _ = btab.(i) <- conf
1071                        in
1072                          fold ll1 ll2 fll (i+1) (SList.cons r' aq) ((conf!=NO)||ab)
1073                      | _ -> aq,ab
1074                  in
1075                  let r,b = fold sl1 sl2 fll 0 SList.nil false in
1076                   Fold2Res.add h_fold2 tag fll sl1 sl2 (r,b,btab); 
1077                  if b then for i=0 to slot_size - 1 do
1078                    res.(i) <- RS.merge btab.(i) t res1.(i) res2.(i);
1079                  done;
1080                  r,res;
1081                end
1082         in
1083
1084         let null_result = (pempty,Array.copy rempty) in
1085         let rec loop t slist ctx =
1086           if t == Tree.nil then null_result else get_trans t slist (Tree.tag tree t) ctx
1087         and loop_tag tag t slist ctx =
1088           if t == Tree.nil then null_result else get_trans t slist tag ctx
1089         and loop_no_right t slist ctx = 
1090           if t == Tree.nil then null_result else get_trans ~noright:true t slist (Tree.tag tree t) ctx
1091         and get_trans ?(noright=false) t slist tag ctx = 
1092           let cont = 
1093             try
1094               TransCache.find td_trans tag slist
1095             with        
1096               | Not_found -> 
1097                   let fl_list,llist,rlist,ca,da,sa,fa = 
1098                     SList.fold 
1099                       (fun set (fll_acc,lllacc,rllacc,ca,da,sa,fa) -> (* For each set *)
1100                          let fl,ll,rr,ca,da,sa,fa = 
1101                            StateSet.fold
1102                              (fun q acc ->                          
1103                                 List.fold_left 
1104                                   (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc) 
1105                                      (ts,t)  ->
1106                                        if (TagSet.mem tag ts)
1107                                        then 
1108                                          let _,_,_,f,_ = t.Transition.node in
1109                                          let (child,desc,below),(sibl,foll,after) = Formula.st f in
1110                                            (Formlist.cons t fl_acc,
1111                                             StateSet.union ll_acc below,
1112                                             StateSet.union rl_acc after,
1113                                             StateSet.union child c_acc,
1114                                             StateSet.union desc d_acc,
1115                                             StateSet.union sibl s_acc,
1116                                             StateSet.union foll f_acc)           
1117                                        else acc ) acc (
1118                                     try Hashtbl.find a.trans q 
1119                                     with
1120                                         Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
1121                                           q;[]
1122                                   )
1123                                   
1124                              ) set (Formlist.nil,StateSet.empty,StateSet.empty,ca,da,sa,fa)
1125                          in (Formlistlist.cons fl fll_acc), (SList.cons ll lllacc), (SList.cons rr rllacc),ca,da,sa,fa)
1126                       slist (Formlistlist.nil,SList.nil,SList.nil,StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
1127                   in                    
1128                     (* Logic to chose the first and next function *)
1129                   let tags_child,tags_below,tags_siblings,tags_after = Tree.tags tree tag in
1130                   let d_f = Algebra.decide a tags_child tags_below (StateSet.union ca da) true in
1131                   let d_n = Algebra.decide a tags_siblings tags_after (StateSet.union sa fa) false in
1132                   let f_kind,first = choose_jump_down tree d_f
1133                   and n_kind,next = if noright then (`NIL, fun _ _ -> Tree.nil )
1134                   else choose_jump_next tree d_n in 
1135                   (*let f_kind,first = `ANY, Tree.first_child tree
1136                   and n_kind,next = `ANY, Tree.next_sibling_below tree 
1137                   in *)
1138                   let empty_res = null_result in
1139                   let cont =
1140                     match f_kind,n_kind with
1141                       | `NIL,`NIL ->
1142                           (fun t _ -> eval_fold2_slist fl_list t (Tree.tag tree t) empty_res empty_res)
1143                       |  _,`NIL -> (
1144                            match f_kind with
1145                              (*|`TAG(tag') ->                           
1146                                 let default = fun t _ -> eval_fold2_slist fl_list t (Tree.tag tree t) empty_res
1147                                   (loop_tag tag' (first t) llist t )
1148                                 in
1149                                 let cf = SList.hd llist in
1150                                 if (slot_size == 1) && StateSet.is_singleton cf
1151                                 then
1152                                 let s = StateSet.choose cf in
1153                                 if (Algebra.is_rec a s fst) && (Algebra.is_rec a s snd)
1154                                 && (Algebra.is_final_marking a s)
1155                                 then 
1156                                 RS.mk_quick_tag_loop default llist 1 tree tag' 
1157                                 else default
1158                                 else default *)
1159                              | _ ->
1160                                  (fun t _ -> eval_fold2_slist fl_list t (Tree.tag tree t) empty_res
1161                                    (loop (first t) llist t ))
1162                          )
1163                       | `NIL,_ -> (
1164                           match n_kind with
1165                             |`TAG(tag') ->
1166                                if SList.equal rlist slist && tag == tag' then
1167                                let rec loop t ctx = 
1168                                  if t == Tree.nil then empty_res else 
1169                                  let res2 = loop (next t ctx) ctx in                               
1170                                  eval_fold2_slist fl_list t tag res2 empty_res            
1171                                in loop
1172                                else 
1173                                (fun t ctx -> eval_fold2_slist fl_list t (Tree.tag tree t)
1174                                  (loop_tag tag' (next t ctx) rlist ctx ) empty_res)
1175                                                                                              
1176                             | _ ->
1177                                 (fun t ctx -> eval_fold2_slist fl_list t (Tree.tag tree t)
1178                                    (loop (next t ctx) rlist ctx ) empty_res)
1179                         )
1180                           
1181                       | `TAG(tag1),`TAG(tag2) ->
1182                           (fun t ctx ->
1183                              eval_fold2_slist fl_list t (Tree.tag tree t)
1184                                (loop_tag tag2 (next t ctx) rlist ctx )
1185                                (loop_tag tag1 (first t) llist t ))
1186  
1187                       | `TAG(tag'),`ANY ->
1188                           (fun t ctx ->
1189                             eval_fold2_slist fl_list t (Tree.tag tree t)
1190                               (loop (next t ctx) rlist ctx )
1191                               (loop_tag tag' (first t) llist t ))
1192                                                                            
1193                       | `ANY,`TAG(tag') ->
1194                           (fun t ctx ->
1195                             eval_fold2_slist fl_list t (Tree.tag tree t)
1196                               (loop_tag tag' (next t ctx) rlist ctx )
1197                               (loop (first t) llist t ))
1198                                                                    
1199                       | `ANY,`ANY ->
1200                           (*if SList.equal slist rlist && SList.equal slist llist
1201                           then
1202                           let rec loop t ctx = 
1203                             if t == Tree.nil then empty_res else
1204                             let r1 = loop (first t) t
1205                             and r2 = loop (next t ctx) ctx
1206                             in
1207                             eval_fold2_slist fl_list t (Tree.tag tree t) r2 r1
1208                           in loop
1209                           else *)
1210                           (fun t ctx ->
1211                              eval_fold2_slist fl_list t (Tree.tag tree t)
1212                                (loop (next t ctx) rlist ctx )
1213                                (loop (first t) llist t ))
1214                       | _,_ -> 
1215                           (fun t ctx ->
1216                              eval_fold2_slist fl_list t (Tree.tag tree t)
1217                                (loop (next t ctx) rlist ctx )
1218                                (loop (first t) llist t ))
1219  
1220                   in
1221                   let cont = D_IF_( (fun t ctx ->
1222                                        let a,b = cont t ctx in
1223                                        register_trace tree t (slist,a,fl_list,first,next,ctx);
1224                                        (a,b)
1225                                     ) ,cont)
1226                   in
1227                   (   TransCache.add td_trans tag slist cont  ;   cont)
1228           in cont t ctx
1229                
1230         in 
1231           (if noright then loop_no_right else loop) t slist ctx
1232
1233         let run_top_down a tree =
1234           let init = SList.cons a.init SList.nil in
1235           let _,res = top_down a tree Tree.root init Tree.root 1 
1236           in 
1237             D_IGNORE_(
1238               output_trace a tree "trace.html"
1239                 (RS.fold (fun t a -> IntSet.add (Tree.id tree t) a) res.(0) IntSet.empty),
1240               res.(0))
1241         ;;
1242
1243         module Configuration =
1244         struct
1245           module Ptss = Set.Make(StateSet)
1246           module IMap = Map.Make(StateSet)
1247           type t = { hash : int;
1248                         sets : Ptss.t;
1249                         results : RS.t IMap.t }
1250           let empty = { hash = 0;
1251                         sets = Ptss.empty;
1252                         results = IMap.empty;
1253                       }
1254           let is_empty c = Ptss.is_empty c.sets
1255           let add c s r =
1256             if Ptss.mem s c.sets then
1257               { c with results = IMap.add s (RS.concat r (IMap.find s c.results)) c.results}
1258             else
1259               { hash = HASHINT2(c.hash,Uid.to_int (Ptset.Int.uid s));
1260                 sets = Ptss.add s c.sets;
1261                 results = IMap.add s r c.results
1262               }
1263
1264           let pr fmt c = Format.fprintf fmt "{";
1265             Ptss.iter (fun s -> StateSet.print fmt s;
1266                         Format.fprintf fmt "  ") c.sets;
1267             Format.fprintf fmt "}\n%!";
1268             IMap.iter (fun k d -> 
1269                          StateSet.print fmt k;
1270                          Format.fprintf fmt "-> %i\n" (RS.length d)) c.results;                  
1271             Format.fprintf fmt "\n%!"
1272               
1273           let merge c1 c2  =
1274             let acc1 =
1275               IMap.fold 
1276                 ( fun s r acc ->
1277                     IMap.add s
1278                       (try 
1279                          RS.concat r (IMap.find s acc)
1280                        with
1281                          | Not_found -> r) acc) c1.results IMap.empty 
1282             in
1283             let imap =
1284                 IMap.fold (fun s r acc -> 
1285                              IMap.add s
1286                                (try 
1287                                   RS.concat r (IMap.find s acc)
1288                                 with
1289                                   | Not_found -> r) acc)  c2.results acc1
1290             in
1291             let h,s =
1292               Ptss.fold 
1293                 (fun s (ah,ass) -> (HASHINT2(ah, Uid.to_int (Ptset.Int.uid s)),
1294                                     Ptss.add s ass))
1295                 (Ptss.union c1.sets c2.sets) (0,Ptss.empty)
1296             in
1297               { hash = h;
1298                 sets =s;
1299                 results = imap }
1300
1301         end
1302
1303         let h_fold = Hashtbl.create 511 
1304
1305         let fold_f_conf  tree t slist fl_list conf dir= 
1306           let tag = Tree.tag tree t in
1307           let rec loop sl fl acc =
1308             match SList.node sl,fl with
1309               |SList.Nil,[] -> acc
1310               |SList.Cons(s,sll), formlist::fll ->
1311                  let r',mcnf = 
1312                    let key = SList.hash sl,Formlist.hash formlist,dir in
1313                    try 
1314                      Hashtbl.find h_fold key
1315                    with
1316                       Not_found -> let res = 
1317                         if dir then eval_formlist tag s Ptset.Int.empty formlist
1318                         else eval_formlist tag Ptset.Int.empty s formlist 
1319                       in (Hashtbl.add h_fold key res;res)
1320                  in
1321                  let (rb,rb1,rb2,mark) = bool_of_merge mcnf in
1322                  if rb && ((dir&&rb1)|| ((not dir) && rb2))
1323                  then 
1324                  let acc = 
1325                    let old_r = 
1326                      try Configuration.IMap.find s conf.Configuration.results
1327                      with Not_found -> RS.empty
1328                    in
1329                    Configuration.add acc r' (if mark then RS.cons t old_r else old_r)                   
1330                  in
1331                  loop sll fll acc
1332                  else loop sll fll acc
1333               | _ -> assert false
1334           in
1335             loop slist fl_list Configuration.empty
1336
1337         let h_trans = Hashtbl.create 4096
1338
1339         let get_up_trans slist ptag a tree =      
1340           let key = (HASHINT2(Uid.to_int slist.SList.Node.id ,ptag)) in
1341             try
1342           Hashtbl.find h_trans key              
1343           with
1344           | Not_found ->  
1345               let f_list =
1346                 Hashtbl.fold (fun q l acc ->
1347                                 List.fold_left (fun fl_acc (ts,t)  ->
1348                                                   if TagSet.mem ptag ts then Formlist.cons t fl_acc
1349                                                   else fl_acc)
1350                                   
1351                                   acc l)
1352                   a.trans Formlist.nil
1353               in
1354               let res = SList.fold (fun _ acc -> f_list::acc) slist [] 
1355               in
1356                 (Hashtbl.add h_trans key res;res) 
1357                   
1358
1359               
1360         let h_tdconf = Hashtbl.create 511 
1361         let rec bottom_up a tree t conf next jump_fun root dotd init accu = 
1362           if (not dotd) && (Configuration.is_empty conf ) then
1363           accu,conf,next 
1364           else
1365
1366           let below_right = Tree.is_below_right tree t next in 
1367           
1368           let accu,rightconf,next_of_next =         
1369             if below_right then (* jump to the next *)
1370             bottom_up a tree next conf (jump_fun next) jump_fun (Tree.next_sibling tree t) true init accu
1371             else accu,Configuration.empty,next
1372           in 
1373           let sub =
1374             if dotd then
1375             if below_right then prepare_topdown a tree t true
1376             else prepare_topdown a tree t false
1377             else conf
1378           in
1379           let conf,next =
1380             (Configuration.merge rightconf sub, next_of_next)
1381           in
1382           if t == root then  accu,conf,next else
1383           let parent = Tree.binary_parent tree t in
1384           let ptag = Tree.tag tree parent in
1385           let dir = Tree.is_left tree t in
1386           let slist = Configuration.Ptss.fold (fun e a -> SList.cons e a) conf.Configuration.sets SList.nil in
1387           let fl_list = get_up_trans slist ptag a parent in
1388           let slist = SList.rev (slist) in 
1389           let newconf = fold_f_conf tree parent slist fl_list conf dir in
1390           let accu,newconf = Configuration.IMap.fold (fun s res (ar,nc) ->
1391                                                         if Ptset.Int.intersect s init then
1392                                                           ( RS.concat res ar ,nc)
1393                                                         else (ar,Configuration.add nc s res))
1394             (newconf.Configuration.results) (accu,Configuration.empty) 
1395           in
1396
1397             bottom_up a tree parent newconf next jump_fun root false init accu
1398               
1399         and prepare_topdown a tree t noright =
1400           let tag = Tree.tag tree t in
1401           let r = 
1402             try
1403               Hashtbl.find h_tdconf tag
1404             with
1405               | Not_found -> 
1406                   let res = Hashtbl.fold (fun q l acc -> 
1407                                             if List.exists (fun (ts,_) -> TagSet.mem tag ts) l
1408                                             then Ptset.Int.add q acc
1409                                             else acc) a.trans Ptset.Int.empty
1410                   in Hashtbl.add h_tdconf tag res;res
1411           in 
1412 (*        let _ = pr ", among ";
1413             StateSet.print fmt (Ptset.Int.elements r);
1414             pr "\n%!";
1415           in *)
1416           let r = SList.cons r SList.nil in
1417           let set,res = top_down (~noright:noright) a tree t r t 1 in
1418           let set = match SList.node set with
1419             | SList.Cons(x,_) ->x
1420             | _ -> assert false 
1421           in
1422           Configuration.add Configuration.empty set res.(0) 
1423
1424
1425
1426         let run_bottom_up a tree k =
1427           let t = Tree.root in
1428           let trlist = Hashtbl.find a.trans (StateSet.choose a.init)
1429           in
1430           let init = List.fold_left 
1431             (fun acc (_,t) ->
1432                let _,_,_,f,_ = Transition.node t in 
1433                let _,_,l = fst ( Formula.st f ) in
1434                  StateSet.union acc l)
1435             StateSet.empty trlist
1436           in
1437           let tree1,jump_fun =
1438             match k with
1439               | `TAG (tag) -> 
1440                   (*Tree.tagged_lowest t tag, fun tree -> Tree.tagged_next tree tag*)
1441                   (Tree.tagged_descendant tree tag t, let jump = Tree.tagged_following_below tree tag
1442                   in fun n -> jump n t )
1443               | `CONTAINS(_) -> (Tree.text_below tree t,let jump = Tree.text_next tree 
1444                                  in fun n -> jump n t)
1445               | _ -> assert false
1446           in
1447           let tree2 = jump_fun tree1 in
1448           let rec loop t next acc = 
1449             let acc,conf,next_of_next = bottom_up a tree t
1450               Configuration.empty next jump_fun (Tree.root) true init acc
1451             in 
1452             let acc = Configuration.IMap.fold 
1453               ( fun s res acc -> if StateSet.intersect init s
1454                 then RS.concat res acc else acc) conf.Configuration.results acc
1455             in
1456               if Tree.is_nil next_of_next  (*|| Tree.equal next next_of_next *)then
1457                 acc
1458               else loop next_of_next (jump_fun next_of_next) acc
1459           in
1460           loop tree1 tree2 RS.empty
1461
1462
1463     end
1464           
1465     let top_down_count a t = let module RI = Run(Integer) in Integer.length (RI.run_top_down a t)
1466     let top_down a t = let module RI = Run(IdSet) in (RI.run_top_down a t)
1467     let bottom_up_count a t k = let module RI = Run(Integer) in Integer.length (RI.run_bottom_up a t k)
1468     let bottom_up a t k = let module RI = Run(IdSet) in (RI.run_bottom_up a t k)
1469
1470     module Test (Doc : sig val doc : Tree.t end) =
1471       struct
1472         module Results = GResult(Doc)
1473         let top_down a t = let module R = Run(Results) in (R.run_top_down a t)
1474       end
1475