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