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