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