Random fixes
[SXSI/xpathcomp.git] / ata.ml
1 INCLUDE "debug.ml"
2 INCLUDE "utils.ml"
3 open Camlp4.Struct
4 type jump_kind = [ `TAG of Tag.t | `CONTAINS of string | `NOTHING ]
5
6 (* Todo : move elsewhere *)
7 external vb : bool -> int = "%identity"
8
9 module State :
10 sig
11   include Sigs.T with type t = int
12   val make : unit -> t
13 end =
14 struct
15   type t = int
16   let make =
17     let id = ref ~-1 in
18     fun () -> incr id; !id
19
20   let compare = (-)
21   let equal = (==)
22   external hash : t -> int =  "%identity"
23   let print fmt x = Format.fprintf fmt "%i" x
24   let dump fmt x = print fmt x
25   let check x =
26     if x < 0 then failwith (Printf.sprintf "State: Assertion %i < 0 failed" x)
27 end
28
29 module StateSet =
30 struct
31   include Ptset.Make ( struct type t = int
32                               type data = t
33                               external hash : t -> int = "%identity"
34                               external uid : t -> Uid.t = "%identity"
35                               external equal : t -> t -> bool = "%eq"
36                               external make : t -> int = "%identity"
37                               external node : t -> int = "%identity"
38                               external with_id : Uid.t -> t = "%identity"
39                        end
40                      )
41   let print ppf s =
42     Format.pp_print_string ppf "{ ";
43     iter (fun i -> Format.fprintf ppf "%i " i) s;
44     Format.pp_print_string ppf "}";
45     Format.pp_print_flush ppf ()
46 end
47
48 module Formula =
49 struct
50     type 'hcons expr =
51       | False | True
52       | Or of 'hcons * 'hcons
53       | And of 'hcons * 'hcons
54       | Atom of ([ `Left | `Right  | `LLeft | `RRight  ]*bool*State.t)
55
56     type 'hcons node = {
57       pos : 'hcons expr;
58       mutable neg : 'hcons;
59       st : (StateSet.t*StateSet.t*StateSet.t)*(StateSet.t*StateSet.t*StateSet.t);
60       size: int; (* Todo check if this is needed *)
61     }
62
63     external hash_const_variant : [> ] -> int = "%identity"
64     module rec Node : Hcons.S with type data = Data.t = Hcons.Make (Data)
65     and Data : Hashtbl.HashedType  with type t = Node.t node =
66     struct
67     type t =  Node.t node
68     let equal x y = x.size == y.size &&
69       match x.pos,y.pos with
70         | a,b when a == b -> true
71         | Or(xf1,xf2),Or(yf1,yf2)
72         | And(xf1,xf2),And(yf1,yf2)  -> (xf1 == yf1) && (xf2 == yf2)
73         | Atom(d1,p1,s1), Atom(d2,p2,s2) -> d1 == d2 && (p1==p2) && s1 == s2
74         | _ -> false
75     let hash f =
76       match f.pos with
77         | False -> 0
78         | True -> 1
79         | Or (f1,f2) -> HASHINT3(PRIME2,Uid.to_int f1.Node.id, Uid.to_int f2.Node.id)
80         | And (f1,f2) -> HASHINT3(PRIME3,Uid.to_int f1.Node.id, Uid.to_int f2.Node.id)
81         | Atom(d,p,s) -> HASHINT4(PRIME4,hash_const_variant d,vb p,s)
82     end
83
84     type t = Node.t
85     let hash x = x.Node.key
86     let uid x = x.Node.id
87     let equal = Node.equal
88     let expr f = f.Node.node.pos
89     let st f = f.Node.node.st
90     let size f = f.Node.node.size
91
92     let prio f =
93       match expr f with
94         | True | False -> 10
95         | Atom _ -> 8
96         | And _ -> 6
97         | Or _ -> 1
98
99     let rec print ?(parent=false) ppf f =
100       if parent then Format.fprintf ppf "(";
101       let _ = match expr f with
102         | True -> Format.fprintf ppf "T"
103         | False -> Format.fprintf ppf "F"
104         | And(f1,f2) ->
105             print ~parent:(prio f > prio f1) ppf f1;
106             Format.fprintf ppf " ∧ ";
107             print ~parent:(prio f > prio f2) ppf f2;
108         | Or(f1,f2) ->
109             (print ppf f1);
110             Format.fprintf ppf " ∨ ";
111             (print ppf f2);
112         | Atom(dir,b,s) -> Format.fprintf ppf "%s%s[%i]"
113             (if b then "" else "¬")
114               (match  dir with
115                  | `Left ->  "↓₁"
116                  | `Right -> "↓₂"
117                  | `LLeft ->  "⇓₁"
118                  | `RRight -> "⇓₂") s
119       in
120         if parent then Format.fprintf ppf ")"
121
122     let print ppf f =  print ~parent:false ppf f
123
124     let is_true f = (expr f) == True
125     let is_false f = (expr f) == False
126
127
128     let cons pos neg s1 s2 size1 size2 =
129       let nnode = Node.make { pos = neg; neg = (Obj.magic 0); st = s2; size = size2 } in
130       let pnode = Node.make { pos = pos; neg = nnode ; st = s1; size = size1 }
131       in
132         (Node.node nnode).neg <- pnode; (* works because the neg field isn't taken into
133                                             account for hashing ! *)
134         pnode,nnode
135
136     let empty_triple = StateSet.empty,StateSet.empty,StateSet.empty
137     let empty_hex = empty_triple,empty_triple
138     let true_,false_ = cons True False empty_hex empty_hex 0 0
139     let atom_ d p s =
140       let si = StateSet.singleton s in
141       let ss = match d with
142         | `Left -> (si,StateSet.empty,si),empty_triple
143         | `Right -> empty_triple,(si,StateSet.empty,si)
144         | `LLeft -> (StateSet.empty,si,si),empty_triple
145         | `RRight -> empty_triple,(StateSet.empty,si,si)
146       in fst (cons (Atom(d,p,s)) (Atom(d,not p,s)) ss ss 1 1)
147
148     let not_ f = f.Node.node.neg
149     let union_hex  ((l1,ll1,lll1),(r1,rr1,rrr1))  ((l2,ll2,lll2),(r2,rr2,rrr2)) =
150       (StateSet.mem_union l1 l2 ,StateSet.mem_union ll1 ll2,StateSet.mem_union lll1 lll2),
151       (StateSet.mem_union r1 r2 ,StateSet.mem_union rr1 rr2,StateSet.mem_union rrr1 rrr2)
152
153     let merge_states f1 f2 =
154       let sp =
155         union_hex (st f1) (st f2)
156       and sn =
157         union_hex (st (not_ f1)) (st (not_ f2))
158       in
159         sp,sn
160
161     let order f1 f2 = if uid f1  < uid f2 then f2,f1 else f1,f2
162
163     let or_ f1 f2 =
164       (* Tautologies: x|x, x|not(x) *)
165
166       if equal f1 f2 then f1 else
167       if equal f1 (not_ f2) then true_ else
168
169       (* simplification *)
170       if is_true f1 || is_true f2 then true_ else
171       if is_false f1 && is_false f2 then false_ else
172       if is_false f1 then f2 else
173       if is_false f2 then f1 else
174
175       (* commutativity of | *)
176
177       let f1,f2 = order f1 f2 in
178       let psize = (size f1) + (size f2) in
179       let nsize = (size (not_ f1)) + (size (not_ f2)) in
180       let sp,sn = merge_states f1 f2 in
181       fst (cons (Or(f1,f2)) (And(not_ f1,not_ f2)) sp sn psize nsize)
182
183
184     let and_ f1 f2 =
185
186       (* Tautologies: x&x, x&not(x) *)
187
188       if equal f1 f2 then f1 else
189       if equal f1 (not_ f2) then false_ else
190
191         (* simplifications *)
192
193       if is_true f1 && is_true f2 then true_ else
194       if is_false f1 || is_false f2 then false_ else
195       if is_true f1 then f2 else
196       if is_true f2 then f1 else
197
198       (* commutativity of & *)
199
200       let f1,f2 = order f1 f2 in
201       let psize = (size f1) + (size f2) in
202       let nsize = (size (not_ f1)) + (size (not_ f2)) in
203       let sp,sn = merge_states f1 f2 in
204         fst (cons (And(f1,f2)) (Or(not_ f1,not_ f2)) sp sn psize nsize)
205     module Infix = struct
206     let ( +| ) f1 f2 = or_ f1 f2
207     let ( *& ) f1 f2 = and_ f1 f2
208     let ( *+ ) d s = atom_ d true s
209     let ( *- ) d s = atom_ d false s
210     end
211 end
212
213 module Transition = struct
214
215   type node = State.t*TagSet.t*bool*Formula.t*bool
216   include Hcons.Make(struct
217                        type t = node
218                        let hash (s,ts,m,f,b) = HASHINT5(s,Uid.to_int (TagSet.uid ts),
219                                                         Uid.to_int (Formula.uid f),
220                                                         vb m,vb b)
221                        let equal (s,ts,b,f,m) (s',ts',b',f',m') =
222                          s == s' && ts == ts' && b==b' && m==m' && f == f'
223                      end)
224
225   let print ppf f = let (st,ts,mark,form,b) = node f in
226     Format.fprintf ppf "(%i, " st;
227     TagSet.print ppf ts;
228     Format.fprintf ppf ") %s" (if mark then "⇒" else "→");
229     Formula.print ppf form;
230     Format.fprintf ppf "%s%!" (if b then " (b)" else "")
231
232
233   module Infix = struct
234   let ( ?< ) x = x
235   let ( >< ) state (l,mark) = state,(l,mark,false)
236   let ( ><@ ) state (l,mark) = state,(l,mark,true)
237   let ( >=> ) (state,(label,mark,bur)) form = (state,label,(make (state,label,mark,form,bur)))
238   end
239
240 end
241
242 module Formlist = struct
243   include Hlist.Make(Transition)
244   let print ppf fl =
245     iter (fun t -> Transition.print ppf t; Format.pp_print_newline ppf ()) fl
246 end
247
248 module Formlistlist =
249 struct
250   include Hlist.Make(Formlist)
251   let print ppf fll =
252     iter (fun fl -> Formlist.print ppf fl; Format.pp_print_newline ppf ())fll
253 end
254
255 type 'a t = {
256     id : int;
257     mutable states : StateSet.t;
258     init : StateSet.t;
259     starstate : StateSet.t option;
260     (* Transitions of the Alternating automaton *)
261     trans : (State.t,(TagSet.t*Transition.t) list) Hashtbl.t;
262     query_string: string;
263  }
264
265
266 let dump ppf a =
267   Format.fprintf ppf "Automaton (%i) :\n" a.id;
268   Format.fprintf ppf "States : "; StateSet.print ppf a.states;
269   Format.fprintf ppf "\nInitial states : "; StateSet.print ppf a.init;
270   Format.fprintf ppf "\nAlternating transitions :\n";
271   let l = Hashtbl.fold (fun k t acc ->
272                           (List.map (fun (ts,tr) -> (ts,k),Transition.node tr) t) @ acc) a.trans [] in
273   let l = List.sort (fun ((tsx,x),_) ((tsy,y),_) ->
274                        if y-x == 0 then TagSet.compare tsy tsx else y-x) l in
275   let maxh,maxt,l_print =
276     List.fold_left (
277       fun (maxh,maxt,l) ((ts,q),(_,_,b,f,_)) ->
278         let s =
279           if TagSet.is_finite ts
280           then "{" ^ (TagSet.fold (fun t a -> a ^ " '" ^ (Tag.to_string t)^"'") ts "") ^" }"
281           else let cts = TagSet.neg ts in
282           if TagSet.is_empty cts then "*" else
283           (TagSet.fold (fun t a -> a ^ " " ^ (Tag.to_string t)) cts "*\\{"
284           )^ "}"
285         in
286         let s = Printf.sprintf "(%s,%i)" s q in
287         let s_frm =
288           Formula.print Format.str_formatter f;
289           Format.flush_str_formatter()
290         in
291           (max (String.length s) maxh, max (String.length s_frm) maxt,
292            (s,(if b then "⇒" else "→"),s_frm)::l)) (0,0,[]) l
293   in
294     Format.fprintf ppf "%s\n%!" (String.make (maxt+maxh+3) '_');
295     List.iter (fun (s,m,f) -> let s = s ^ (String.make (maxh-(String.length s)) ' ') in
296                  Format.fprintf ppf "%s %s %s\n" s m f) l_print;
297     Format.fprintf ppf "%s\n%!" (String.make (maxt+maxh+3) '_')
298
299
300 module FormTable = Hashtbl.Make(struct
301                                   type t = Formula.t*StateSet.t*StateSet.t
302                                   let equal (f1,s1,t1) (f2,s2,t2) =
303                                     f1 == f2 && s1 == s2 && t1 == t2
304                                   let hash (f,s,t) =
305                                     HASHINT3(Uid.to_int (Formula.uid f),
306                                              Uid.to_int (StateSet.uid s),
307                                              Uid.to_int (StateSet.uid t))
308                                 end)
309 module F = Formula
310
311 let eval_form_bool =
312   let h_f = FormTable.create BIG_H_SIZE in
313     fun f s1 s2 ->
314       let rec loop f =
315         match F.expr f with
316           | F.True -> true,true,true
317           | F.False -> false,false,false
318           | F.Atom((`Left|`LLeft),b,q) ->
319               if b == (StateSet.mem q s1)
320               then (true,true,false)
321               else false,false,false
322           | F.Atom(_,b,q) ->
323               if b == (StateSet.mem q s2)
324               then (true,false,true)
325               else false,false,false
326           | f' ->
327               try FormTable.find h_f (f,s1,s2)
328               with Not_found -> let r =
329                 match f' with
330                   | F.Or(f1,f2) ->
331                       let b1,rl1,rr1 = loop f1
332                       in
333                         if b1 && rl1 && rr1 then (true,true,true)  else
334                           let b2,rl2,rr2 = loop f2  in
335                           let rl1,rr1 = if b1 then rl1,rr1 else false,false
336                           and rl2,rr2 = if b2 then rl2,rr2 else false,false
337                           in (b1 || b2, rl1||rl2,rr1||rr2)
338
339                   | F.And(f1,f2) ->
340                       let b1,rl1,rr1 = loop f1 in
341                         if b1 && rl1 && rr1 then (true,true,true) else
342                           if b1 then
343                             let b2,rl2,rr2 = loop f2 in
344                               if b2 then (true,rl1||rl2,rr1||rr2) else (false,false,false)
345                           else (false,false,false)
346                   | _ -> assert false
347               in FormTable.add h_f (f,s1,s2) r;r
348       in loop f
349
350
351 module FTable = Hashtbl.Make(struct
352                                type t = Tag.t*Formlist.t*StateSet.t*StateSet.t
353                                let equal (tg1,f1,s1,t1) (tg2,f2,s2,t2) =
354                                  tg1 == tg2 && f1 == f2 &&  s1 == s2 && t1 == t2;;
355                                let hash (tg,f,s,t) =
356                                  HASHINT4(tg, Uid.to_int (Formlist.uid f),
357                                           Uid.to_int (StateSet.uid s),
358                                           Uid.to_int (StateSet.uid t))
359                              end)
360
361
362 let h_f = FTable.create BIG_H_SIZE
363 type merge_conf = NO | ONLY1 | ONLY2 | ONLY12 | MARK | MARK1 | MARK2 | MARK12
364 (* 000 001 010 011 100 101 110 111 *)
365 let eval_formlist tag s1 s2 fl =
366   let rec loop fl =
367           try
368             FTable.find h_f (tag,fl,s1,s2)
369           with
370             | Not_found  ->
371                 match Formlist.node fl with
372                   | Formlist.Cons(f,fll) ->
373                       let q,ts,mark,f,_ = Transition.node f in
374                       let b,b1,b2 =
375                         if TagSet.mem tag ts then eval_form_bool f s1 s2 else (false,false,false)
376                       in
377                       let (s,(b',b1',b2',amark)) as res = loop fll in
378                       let r = if b then (StateSet.add q s, (b, b1'||b1,b2'||b2,mark||amark))
379                       else res
380                       in FTable.add h_f (tag,fl,s1,s2) r;r
381                   | Formlist.Nil -> StateSet.empty,(false,false,false,false)
382   in
383   let r,conf = loop fl
384   in
385   r,(match  conf with
386     | (false,_,_,_) -> NO
387     | (_,false,false,false) -> NO
388     | (_,true,false,false) -> ONLY1
389     | (_,false,true,false) -> ONLY2
390     | (_,true,true,false) -> ONLY12
391     | (_,false,false,true) -> MARK
392     | (_,true,false,true) -> MARK1
393     | (_,false,true,true) -> MARK2
394     | _ -> MARK12)
395
396 let bool_of_merge conf =
397   match  conf with
398     | NO -> false,false,false,false
399     | ONLY1 -> true,true,false,false
400     | ONLY2 -> true,false,true,false
401     | ONLY12 -> true,true,true,false
402     | MARK -> true,false,false,true
403     | MARK1 -> true,true,false,true
404     | MARK2 -> true,false,true,true
405     | MARK12 -> true,true,true,true
406
407
408 let tags_of_state a q =
409   Hashtbl.fold
410     (fun p l acc ->
411        if p == q then List.fold_left
412          (fun acc (ts,t) ->
413             let _,_,_,_,aux = Transition.node t in
414               if aux then acc else
415                 TagSet.cup ts acc) acc l
416
417        else acc) a.trans TagSet.empty
418
419
420
421     let tags a qs =
422       let ts = Ptset.Int.fold (fun q acc -> TagSet.cup acc (tags_of_state a q)) qs TagSet.empty
423       in
424         if TagSet.is_finite ts
425         then `Positive(TagSet.positive ts)
426         else `Negative(TagSet.negative ts)
427
428     let inter_text a b =
429       match b with
430         | `Positive s -> let r = Ptset.Int.inter a s in (r,Ptset.Int.mem Tag.pcdata r, true)
431         | `Negative s -> let r = Ptset.Int.diff a s in (r, Ptset.Int.mem Tag.pcdata r, false)
432
433
434     module type ResultSet =
435     sig
436       type t
437       type elt = [` Tree ] Tree.node
438       val empty : t
439       val cons : elt -> t -> t
440       val concat : t -> t -> t
441       val iter : ( elt -> unit) -> t -> unit
442       val fold : ( elt -> 'a -> 'a) -> t -> 'a -> 'a
443       val map : ( elt -> elt) -> t -> t
444       val length : t -> int
445       val merge : merge_conf -> elt -> t -> t -> t
446       val mk_quick_tag_loop : (elt -> elt -> 'a*t array) -> 'a -> int -> Tree.t -> Tag.t -> (elt -> elt -> 'a*t array)
447       val mk_quick_star_loop : (elt -> elt -> 'a*t array) -> 'a -> int -> Tree.t -> (elt -> elt -> 'a*t array)
448
449     end
450
451     module Integer : ResultSet =
452     struct
453       type t = int
454       type elt = [`Tree] Tree.node
455
456       let empty = 0
457       let cons _ x = x+1
458       let concat x y = x + y
459       let iter _ _ = failwith "iter not implemented"
460       let fold _ _ _ = failwith "fold not implemented"
461       let map _ _ = failwith "map not implemented"
462       let length x = x
463       let merge2 conf t res1 res2 =
464         let rb,rb1,rb2,mark = conf in
465         if rb then
466           let res1 = if rb1 then res1 else 0
467           and res2 = if rb2 then res2 else 0
468           in
469             if mark then 1+res1+res2
470             else res1+res2
471         else 0
472       let merge conf t res1 res2 =
473         match conf with
474           | NO -> 0
475           | ONLY1 -> res1
476           | ONLY2 -> res2
477           | ONLY12 -> res1+res2
478           | MARK -> 1
479           | MARK1 -> res1+1
480           | MARK2 -> res2+1
481           | MARK12 -> res1+res2+1
482       let merge conf _ res1 res2 =
483         let conf = Obj.magic conf in
484         (conf lsr 2) + ((conf land 0b10) lsr 1)*res2 + (conf land 0b1)*res1
485
486
487       let mk_quick_tag_loop _ sl ss tree tag = ();
488         fun t ctx ->
489           (sl, Array.make ss (Tree.subtree_tags tree tag t))
490       let mk_quick_star_loop _ sl ss tree = ();
491         fun t ctx ->
492           (sl, Array.make ss (Tree.subtree_elements tree t))
493
494     end
495
496     module IdSet : ResultSet=
497     struct
498       type elt = [`Tree] Tree.node
499       type node = Nil
500                   | Cons of elt * node
501                   | Concat of node*node
502
503       and t = { node : node;
504                 length :  int }
505
506       let empty = { node = Nil; length = 0 }
507
508       let cons e t = { node = Cons(e,t.node); length = t.length+1 }
509       let concat t1 t2 = { node = Concat(t1.node,t2.node); length = t1.length+t2.length }
510       let append e t = { node = Concat(t.node,Cons(e,Nil)); length = t.length+1 }
511
512       let fold f l acc =
513         let rec loop acc t = match t with
514           | Nil -> acc
515           | Cons (e,t) -> loop (f e acc) t
516           | Concat (t1,t2) -> loop (loop acc t1) t2
517         in
518           loop acc l.node
519
520       let length l = l.length
521
522
523       let iter f l =
524         let rec loop = function
525           | Nil -> ()
526           | Cons (e,t) -> f e; loop t
527           | Concat(t1,t2) -> loop t1;loop t2
528         in loop l.node
529
530       let map f l =
531         let rec loop = function
532           | Nil -> Nil
533           | Cons(e,t) -> Cons(f e, loop t)
534           | Concat(t1,t2) -> Concat(loop t1,loop t2)
535         in
536           { l with node = loop l.node }
537
538       let merge conf t res1 res2 =
539         match conf with
540            NO -> empty
541           | MARK -> cons t empty
542           | ONLY1 -> res1
543           | ONLY2 -> res2
544           | ONLY12 -> { node = (Concat(res1.node,res2.node));
545                         length = res1.length + res2.length ;}
546           | MARK12 -> { node = Cons(t,(Concat(res1.node,res2.node)));
547                         length = res1.length + res2.length + 1;}
548           | MARK1 -> { node = Cons(t,res1.node);
549                         length = res1.length + 1;}
550           | MARK2 -> { node = Cons(t,res2.node);
551                        length = res2.length + 1;}
552
553       let mk_quick_tag_loop f _ _ _ _ = f
554       let mk_quick_star_loop f _ _ _ = f
555     end
556     module GResult(Doc : sig val doc : Tree.t end) = struct
557       type bits
558       type elt = [` Tree] Tree.node
559       external create_empty : int -> bits = "caml_result_set_create" "noalloc"
560       external set : bits -> int -> unit = "caml_result_set_set" "noalloc"
561       external next : bits -> int -> int = "caml_result_set_next" "noalloc"
562       external count : bits -> int  = "caml_result_set_count" "noalloc"
563       external clear : bits -> elt -> elt -> unit = "caml_result_set_clear" "noalloc"
564
565       external set_tag_bits : bits -> Tag.t -> Tree.t -> elt -> elt = "caml_set_tag_bits" "noalloc"
566       type t =
567          { segments : elt list;
568            bits : bits;
569          }
570
571       let ebits =
572         let size = (Tree.subtree_size Doc.doc Tree.root) in
573         create_empty (size*2+1)
574
575       let empty = { segments = [];
576                     bits = ebits }
577
578       let cons e t =
579         let rec loop l = match l with
580           | [] -> { bits = (set t.bits (Obj.magic e);t.bits);
581                     segments = [ e ] }
582           | p::r ->
583               if Tree.is_binary_ancestor Doc.doc e p then
584               loop r
585               else
586               { bits = (set t.bits (Obj.magic e);t.bits);
587                 segments = e::l }
588         in
589         loop t.segments
590
591       let concat t1 t2 =
592         if t2.segments == [] then t1
593         else
594         if t1.segments == [] then t2
595         else
596         let h2 = List.hd t2.segments in
597         let rec loop l = match l with
598           | [] -> t2.segments
599           | p::r ->
600               if Tree.is_binary_ancestor Doc.doc p h2 then
601               l
602               else
603               p::(loop r)
604         in
605         { bits = t1.bits;
606           segments = loop t1.segments
607         }
608
609       let iter f t =
610         let rec loop i =
611           if i == -1 then ()
612           else (f ((Obj.magic i):elt);loop (next t.bits i))
613         in loop (next t.bits 0)
614
615       let fold f t acc =
616         let rec loop i acc =
617           if i == -1 then acc
618           else loop (next t.bits i) (f ((Obj.magic i):elt) acc)
619         in loop (next t.bits 0) acc
620
621       let map _ _ = failwith "noop"
622       (*let length t = let cpt = ref 0 in
623       iter (fun _ -> incr cpt) t; !cpt *)
624       let length t = count t.bits
625
626       let clear_bits t =
627         let rec loop l = match l with
628            [] -> ()
629           | idx::ll ->
630               clear t.bits idx (Tree.closing Doc.doc idx); loop ll
631         in
632         loop t.segments;empty
633
634       let merge (rb,rb1,rb2,mark) elt t1 t2 =
635         if rb then
636 (*      let _ = Printf.eprintf "Lenght before merging is %i %i\n"
637           (List.length t1.segments) (List.length t2.segments)
638         in *)
639         match t1.segments,t2.segments with
640            [],[] -> if mark then cons elt empty else empty
641           | [_],[] when rb1 -> if mark then cons elt t1 else t1
642           | [], [_] when rb2 -> if mark then cons elt t2 else t2
643           | [_],[_] when rb1 && rb2 -> if mark then cons elt empty else
644             concat t1 t2
645           | _ ->
646         let t1 = if rb1 then t1 else clear_bits t1
647         and t2 = if rb2 then t2 else clear_bits t2
648         in
649         (if mark then cons elt (concat t1 t2)
650          else concat t1 t2)
651         else
652         let _ = clear_bits t1 in
653         clear_bits t2
654
655       let merge conf t t1 t2 =
656         match t1.segments,t2.segments,conf with
657           | _,_,NO -> let _ = clear_bits t1 in clear_bits t2
658           | [],[],(MARK1|MARK2|MARK12|MARK) -> cons t empty
659           | [],[],_ -> empty
660           | [_],[],(ONLY1|ONLY12) -> t1
661           | [_],[],(MARK1|MARK12) -> cons t t1
662           | [],[_],(ONLY2|ONLY12) -> t2
663           | [],[_],(MARK2|MARK12) -> cons t t2
664           | [_],[_],ONLY12 -> concat t1 t2
665           | [_],[_],MARK12 -> cons t empty
666           | _,_,MARK -> let _ = clear_bits t2 in cons t (clear_bits t1)
667           | _,_,ONLY1 -> let _ = clear_bits t2 in t1
668           | _,_,ONLY2 -> let _ = clear_bits t1 in t2
669           | _,_,ONLY12 -> concat t1 t2
670           | _,_,MARK1 -> let _ = clear_bits t2 in cons t t1
671           | _,_,MARK2 -> let _ = clear_bits t1 in cons t t2
672           | _,_,MARK12 ->  cons t (concat t1 t2)
673
674       let mk_quick_tag_loop _ sl ss tree tag = ();
675         fun t _ ->
676           let res = empty in
677           let first = set_tag_bits empty.bits tag tree t in
678           let res =
679             if first == Tree.nil then res else
680             cons first res
681           in
682           (sl, Array.make ss res)
683
684       let mk_quick_star_loop f _ _ _ = f
685     end
686     module Run (RS : ResultSet) =
687     struct
688
689       module SList = struct
690         include Hlist.Make (StateSet)
691         let print ppf l =
692           Format.fprintf ppf "[ ";
693           begin
694             match l.Node.node with
695               | Nil -> ()
696               | Cons(s,ll) ->
697                   StateSet.print ppf s;
698                   iter (fun s -> Format.fprintf ppf "; ";
699                         StateSet.print ppf s) ll
700           end;
701           Format.fprintf ppf "]%!"
702
703
704       end
705
706
707 IFDEF DEBUG
708 THEN
709       module IntSet = Set.Make(struct type t = int let compare = (-) end)
710 INCLUDE "html_trace.ml"
711
712 END
713       module Trace =
714       struct
715         module HFname = Hashtbl.Make (struct
716                                         type t = Obj.t
717                                         let hash = Hashtbl.hash
718                                         let equal = (==)
719                                       end)
720
721         let h_fname = HFname.create 401
722
723         let register_funname f s =
724           HFname.add h_fname (Obj.repr  f) s
725         let get_funname f = try HFname.find h_fname  (Obj.repr f) with _ -> "[anon_fun]"
726
727
728
729         let mk_fun f s = register_funname f s;f
730         let mk_app_fun f arg s =
731           let g = f arg in
732           register_funname g ((get_funname f) ^ " " ^ s); g
733         let mk_app_fun2 f arg1 arg2 s =
734           let g = f arg1 arg2 in
735           register_funname g ((get_funname f) ^ " " ^ s); g
736
737       end
738
739       let string_of_ts tags = (Ptset.Int.fold (fun t a -> a ^ " " ^ (Tag.to_string t) ) tags "{")^ " }"
740
741
742       module Algebra =
743         struct
744           type jump = [ `NIL | `ANY |`ANYNOTEXT | `JUMP ]
745           type t = jump*Ptset.Int.t*Ptset.Int.t
746           let jts = function
747           | `JUMP -> "JUMP"
748           | `NIL -> "NIL"
749           | `ANY -> "ANY"
750           | `ANYNOTEXT -> "ANYNOTEXT"
751           let merge_jump (j1,c1,l1) (j2,c2,l2) =
752             match j1,j2 with
753               | _,`NIL -> (j1,c1,l1)
754               | `NIL,_ -> (j2,c2,l2)
755               | `ANY,_ -> (`ANY,Ptset.Int.empty,Ptset.Int.empty)
756               | _,`ANY -> (`ANY,Ptset.Int.empty,Ptset.Int.empty)
757               | `ANYNOTEXT,_ ->
758                   if Ptset.Int.mem Tag.pcdata (Ptset.Int.union c2 l2) then
759                   (`ANY,Ptset.Int.empty,Ptset.Int.empty)
760                   else
761                   (`ANYNOTEXT,Ptset.Int.empty,Ptset.Int.empty)
762               | _,`ANYNOTEXT ->
763                   if Ptset.Int.mem Tag.pcdata (Ptset.Int.union c1 l1) then
764                   (`ANY,Ptset.Int.empty,Ptset.Int.empty)
765                   else
766                   (`ANYNOTEXT,Ptset.Int.empty,Ptset.Int.empty)
767               | `JUMP,`JUMP -> (`JUMP, Ptset.Int.union c1 c2,Ptset.Int.union l1 l2)
768
769           let merge_jump_list = function
770             | [] -> `NIL,Ptset.Int.empty,Ptset.Int.empty
771             | p::r ->
772                 List.fold_left (merge_jump) p r
773
774           let labels a s =
775             Hashtbl.fold
776             (
777               fun q l acc ->
778                 if (q == s)
779                 then
780
781                   (List.fold_left
782                       (fun acc (ts,f) ->
783                         let _,_,_,_,bur = Transition.node f in
784                         if bur then acc else TagSet.cup acc ts)
785                     acc l)
786                 else acc ) a.trans TagSet.empty
787           exception Found
788
789           let is_rec a s access =
790             List.exists
791               (fun (_,t) -> let _,_,_,f,_ = Transition.node t in
792               StateSet.mem s ((fun (_,_,x) -> x) (access (Formula.st f)))) (Hashtbl.find a.trans s)
793
794           let is_final_marking a s =
795             List.exists (fun (_,t) -> let _,_,m,f,_ = Transition.node t in m&& (Formula.is_true f))
796               (Hashtbl.find a.trans s)
797
798
799           let decide a c_label l_label dir_states dir =
800
801             let l = StateSet.fold
802               (fun s l ->
803                  let s_rec = is_rec a s (if dir then fst else snd) in
804                  let s_rec = if dir then s_rec else
805                  (* right move *)
806                  is_rec a s fst
807                  in
808                  let s_lab = labels a s in
809                  let jmp,cc,ll =
810                    if (not (TagSet.is_finite s_lab)) then
811                    if TagSet.mem Tag.pcdata s_lab then  (`ANY,Ptset.Int.empty,Ptset.Int.empty)
812                    else (`ANYNOTEXT,Ptset.Int.empty,Ptset.Int.empty)
813                    else
814                    if s_rec
815                    then (`JUMP,Ptset.Int.empty, TagSet.positive
816                            (TagSet.cap (TagSet.inj_positive l_label) s_lab))
817                    else (`JUMP,TagSet.positive
818                            (TagSet.cap (TagSet.inj_positive c_label) s_lab),
819                          Ptset.Int.empty )
820                  in
821                    (if jmp != `ANY
822                     && jmp != `ANYNOTEXT
823                     && Ptset.Int.is_empty cc
824                     && Ptset.Int.is_empty ll
825                     then (`NIL,Ptset.Int.empty,Ptset.Int.empty)
826                     else  (jmp,cc,ll))::l) dir_states []
827             in merge_jump_list l
828
829
830         end
831
832
833
834       let choose_jump (d,cl,ll) f_nil f_t1 f_s1 f_tn f_sn f_s1n f_notext f_maytext =
835         match d with
836           | `NIL -> (`NIL,f_nil)
837           | `ANYNOTEXT -> `ANY,f_notext
838           | `ANY -> `ANY,f_maytext
839           | `JUMP ->
840               if Ptset.Int.is_empty cl then
841               if Ptset.Int.is_singleton ll then
842               let tag = Ptset.Int.choose ll in
843               (`TAG(tag),Trace.mk_app_fun f_tn tag (Tag.to_string tag))
844               else
845               (`MANY(ll),Trace.mk_app_fun f_sn ll (string_of_ts ll))
846               else if Ptset.Int.is_empty ll then
847               if Ptset.Int.is_singleton cl then
848               let tag = Ptset.Int.choose cl in
849               (`TAG(tag),Trace.mk_app_fun f_t1 tag (Tag.to_string tag))
850               else
851               (`MANY(cl),Trace.mk_app_fun f_s1 cl (string_of_ts cl))
852               else
853               (`ANY,Trace.mk_app_fun2 f_s1n cl ll ((string_of_ts cl) ^ " " ^ (string_of_ts ll)))
854
855           | _ -> assert false
856
857       let choose_jump_down tree d =
858         choose_jump d
859           (Trace.mk_fun (fun _ -> Tree.nil) "Tree.mk_nil")
860           (Trace.mk_fun (Tree.tagged_child tree) "Tree.tagged_child")
861           (Trace.mk_fun (Tree.select_child tree) "Tree.select_child")
862           (Trace.mk_fun (Tree.tagged_descendant tree) "Tree.tagged_desc")
863           (Trace.mk_fun (Tree.select_descendant tree) "Tree.select_desc")
864           (Trace.mk_fun (fun _ _ -> Tree.first_child tree) "[FIRSTCHILD]Tree.select_child_desc")
865           (Trace.mk_fun (Tree.first_element tree) "Tree.first_element")
866           (Trace.mk_fun (Tree.first_child tree) "Tree.first_child")
867
868       let choose_jump_next tree d =
869         choose_jump d
870           (Trace.mk_fun (fun _ _ -> Tree.nil) "Tree.mk_nil2")
871           (Trace.mk_fun (Tree.tagged_following_sibling_below tree) "Tree.tagged_sibling_ctx")
872           (Trace.mk_fun (Tree.select_following_sibling_below tree) "Tree.select_sibling_ctx")
873           (Trace.mk_fun (Tree.tagged_following_below tree) "Tree.tagged_foll_ctx")
874           (Trace.mk_fun (Tree.select_following_below tree) "Tree.select_foll_ctx")
875           (Trace.mk_fun (fun _ _ -> Tree.next_sibling_below tree) "[NEXTSIBLING]Tree.select_sibling_foll_ctx")
876           (Trace.mk_fun (Tree.next_element_below tree) "Tree.next_element_ctx")
877           (Trace.mk_fun (Tree.next_sibling_below tree) "Tree.node_sibling_ctx")
878
879
880
881
882       module CodeCache =
883       struct
884         let get = Array.unsafe_get
885         let set = Array.set
886
887         type fun_tree = [`Tree] Tree.node -> [`Tree] Tree.node -> SList.t ->  Tag.t -> bool -> SList.t*RS.t array
888         type t = fun_tree array array
889
890         let dummy = fun _ _ _ _ _ -> failwith "Uninitializd CodeCache"
891         let default_line = Array.create 1024 dummy (* 1024 = max_tag *)
892         let create n = Array.create n default_line
893         let init f =
894           for i = 0 to (Array.length default_line) - 1
895           do
896             default_line.(i) <- f
897           done
898
899         let get_fun h slist tag =
900           get (get h (Uid.to_int slist.SList.Node.id)) tag
901
902         let set_fun (h : t) slist tag (data : fun_tree) =
903           let tab = get h (Uid.to_int slist.SList.Node.id) in
904           let line = if tab == default_line then
905             let x = Array.copy tab in
906             (set h (Uid.to_int slist.SList.Node.id) x;x)
907           else tab
908           in
909           set line tag data
910
911       end
912
913       let empty_size n =
914         let rec loop acc = function 0 -> acc
915           | n -> loop (SList.cons StateSet.empty acc) (n-1)
916         in loop SList.nil n
917
918
919       module Fold2Res = struct
920         let get = Array.unsafe_get
921         let set = Array.set
922         external field1 : Obj.t -> int = "%field1"
923         type t = Obj.t array array array array
924         let dummy_val = Obj.repr ((),2,())
925
926         let default_line3 = Array.create BIG_A_SIZE dummy_val
927         let default_line2 = Array.create BIG_A_SIZE default_line3
928         let default_line1 = Array.create BIG_A_SIZE default_line2
929
930         let create n = Array.create n default_line1
931
932         let find h tag fl s1 s2 : SList.t*bool*(merge_conf array) =
933           let l1 = get h tag in
934           let l2 = get l1 (Uid.to_int fl.Formlistlist.Node.id) in
935           let l3 = get l2 (Uid.to_int s1.SList.Node.id) in
936           Obj.magic (get l3 (Uid.to_int s2.SList.Node.id))
937
938         let is_valid b = (Obj.magic b) != 2
939         let get_replace tab idx default =
940           let e = get tab idx in
941           if e == default then
942           let ne = Array.copy e in (set tab idx ne;ne)
943           else e
944
945         let add h tag fl s1 s2 (data: SList.t*bool*(merge_conf array)) =
946           let l1 = get_replace h tag default_line1 in
947           let l2 = get_replace l1 (Uid.to_int fl.Formlistlist.Node.id) default_line2 in
948           let l3 = get_replace l2 (Uid.to_int s1.SList.Node.id) default_line3  in
949           set l3 (Uid.to_int s2.SList.Node.id) (Obj.repr data)
950       end
951
952
953
954
955       let top_down ?(noright=false) a tree t slist ctx slot_size td_trans h_fold2=
956         let pempty = empty_size slot_size in
957         let rempty = Array.make slot_size RS.empty in
958         (* evaluation starts from the right so we put sl1,res1 at the end *)
959         let eval_fold2_slist fll t tag (sl2,res2) (sl1,res1) =
960           let res = Array.copy rempty in
961           let r,b,btab = Fold2Res.find h_fold2 tag fll sl1 sl2  in
962           if Fold2Res.is_valid b then
963           begin
964             if b then for i=0 to slot_size - 1 do
965               res.(0) <- RS.merge btab.(0) t res1.(0) res2.(0);
966             done;
967             r,res
968           end
969           else
970           begin
971             let btab = Array.make slot_size NO in
972             let rec fold l1 l2 fll i aq ab =
973               match fll.Formlistlist.Node.node,
974                 l1.SList.Node.node,
975                 l2.SList.Node.node
976               with
977                 | Formlistlist.Cons(fl,fll),
978                  SList.Cons(s1,ll1),
979                  SList.Cons(s2,ll2) ->
980                     let r',conf = eval_formlist tag s1 s2 fl in
981                     let _ = btab.(i) <- conf
982                     in
983                     fold ll1 ll2 fll (i+1) (SList.cons r' aq) ((conf!=NO)||ab)
984                 | _ -> aq,ab
985             in
986             let r,b = fold sl1 sl2 fll 0 SList.nil false in
987             Fold2Res.add h_fold2 tag fll sl1 sl2 (r,b,btab);
988             if b then for i=0 to slot_size - 1 do
989               res.(i) <- RS.merge btab.(i) t res1.(i) res2.(i);
990             done;
991             r,res;
992           end
993         in
994
995         let null_result = (pempty,Array.copy rempty) in
996         let empty_res = null_result in
997
998         let rec loop t ctx slist _  =
999           if t == Tree.nil then null_result else
1000           let tag = Tree.tag tree t in
1001           (CodeCache.get_fun td_trans slist tag) t ctx slist tag false
1002             (* get_trans t ctx slist tag false
1003             (CodeCache.get_opcode td_trans slist tag)
1004             *)
1005         and loop_tag t ctx slist tag  =
1006           if t == Tree.nil then null_result else
1007           (CodeCache.get_fun td_trans slist tag) t ctx slist tag false
1008             (* get_trans t ctx slist tag false
1009             (CodeCache.get_opcode td_trans slist tag) *)
1010
1011         and loop_no_right t ctx slist _  =
1012           if t == Tree.nil then null_result else
1013           let tag = Tree.tag tree t in
1014           (CodeCache.get_fun td_trans slist tag) t ctx slist tag true
1015             (* get_trans t ctx slist tag true
1016                (CodeCache.get_opcode td_trans slist tag) *)
1017             (*
1018         and get_trans t ctx slist tag noright opcode =
1019           match opcode with
1020             | OpCode.K0 fll ->
1021                 eval_fold2_slist fll t tag empty_res empty_res
1022
1023             | OpCode.K1 (fll,first,llist,tag1) ->
1024                 eval_fold2_slist fll t tag empty_res
1025                   (loop_tag (first t) t llist tag1)
1026
1027             | OpCode.K2 (fll,first,llist) ->
1028                 eval_fold2_slist fll t tag empty_res
1029                   (loop (first t) t llist)
1030
1031             | OpCode.K3 (fll,next,rlist,tag2) ->
1032                 eval_fold2_slist fll t tag
1033                   (loop_tag (next t ctx) ctx rlist tag2)
1034                   empty_res
1035             | OpCode.K4 (fll,next,rlist) ->
1036                 eval_fold2_slist fll t tag
1037                   (loop (next t ctx) ctx rlist)
1038                   empty_res
1039
1040             | OpCode.K5 (fll,next,rlist,tag2,first,llist,tag1) ->
1041                 eval_fold2_slist fll t tag
1042                   (loop_tag (next t ctx) ctx rlist tag2)
1043                   (loop_tag (first t) t llist tag1)
1044
1045             | OpCode.K6 (fll,next,rlist,first,llist,tag1) ->
1046                 eval_fold2_slist fll t tag
1047                   (loop (next t ctx) ctx rlist)
1048                   (loop_tag (first t) t llist tag1)
1049
1050             | OpCode.K7 (fll,next,rlist,tag2,first,llist) ->
1051                 eval_fold2_slist fll t tag
1052                   (loop_tag (next t ctx) ctx rlist tag2)
1053                   (loop (first t) t llist)
1054
1055             | OpCode.K8 (fll,next,rlist,first,llist) ->
1056                 eval_fold2_slist fll t tag
1057                   (loop (next t ctx) ctx rlist)
1058                   (loop (first t) t llist)
1059
1060             | OpCode.KDefault _ ->
1061                 mk_trans t ctx tag slist noright
1062             *)
1063         and mk_trans t ctx slist tag noright =
1064           let fl_list,llist,rlist,ca,da,sa,fa =
1065             SList.fold
1066               (fun set (fll_acc,lllacc,rllacc,ca,da,sa,fa) -> (* For each set *)
1067                  let fl,ll,rr,ca,da,sa,fa =
1068                    StateSet.fold
1069                      (fun q acc ->
1070                         List.fold_left
1071                           (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc)
1072                            (ts,t)  ->
1073                              if (TagSet.mem tag ts)
1074                              then
1075                              let _,_,_,f,_ = t.Transition.node in
1076                              let (child,desc,below),(sibl,foll,after) = Formula.st f in
1077                              (Formlist.cons t fl_acc,
1078                               StateSet.union ll_acc below,
1079                               StateSet.union rl_acc after,
1080                               StateSet.union child c_acc,
1081                               StateSet.union desc d_acc,
1082                               StateSet.union sibl s_acc,
1083                               StateSet.union foll f_acc)
1084                              else acc ) acc (
1085                             try Hashtbl.find a.trans q
1086                             with
1087                                Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
1088                                  q;[]
1089                           )
1090
1091                      ) set (Formlist.nil,StateSet.empty,StateSet.empty,ca,da,sa,fa)
1092                  in (Formlistlist.cons fl fll_acc), (SList.cons ll lllacc), (SList.cons rr rllacc),ca,da,sa,fa)
1093               slist (Formlistlist.nil,SList.nil,SList.nil,StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
1094           in
1095           (* Logic to chose the first and next function *)
1096           let tags_child,tags_below,tags_siblings,tags_after = Tree.tags tree tag in
1097           let d_f = Algebra.decide a tags_child tags_below (StateSet.union ca da) true in
1098           let d_n = Algebra.decide a tags_siblings tags_after (StateSet.union sa fa) false in
1099           let f_kind,first = choose_jump_down tree d_f
1100           and n_kind,next = if noright then (`NIL, fun _ _ -> Tree.nil )
1101           else choose_jump_next tree d_n in
1102           let empty_res = null_result in
1103           let fll = fl_list in
1104           let cont =
1105             match f_kind,n_kind with
1106               | `NIL,`NIL -> (*OpCode.K0(fl_list) *)
1107                   fun t _ _ tag _ -> eval_fold2_slist fll t tag empty_res empty_res
1108
1109               |  _,`NIL -> (
1110                    match f_kind with
1111                      |`TAG(tag1) -> (*OpCode.K1(fl_list,first,llist,tag1) *)
1112                         fun t _ _ tag _ -> eval_fold2_slist fll t tag empty_res
1113                           (loop_tag (first t) t llist tag1)
1114                      | _ -> (* OpCode.K2(fl_list,first,llist) *)
1115                          fun t _ _ tag _  -> eval_fold2_slist fll t tag empty_res
1116                            (loop (first t) t llist tag)
1117                  )
1118               | `NIL,_ -> (
1119                   match n_kind with
1120                     |`TAG(tag2) -> (*OpCode.K3(fl_list,next,rlist,tag2) *)
1121                        fun t ctx _ tag _ ->
1122                          eval_fold2_slist fll t tag
1123                            (loop_tag (next t ctx) ctx rlist tag2)
1124                            empty_res
1125
1126                     | _ -> (*OpCode.K4(fl_list,next,rlist) *)
1127                         fun t ctx _ tag _ ->
1128                           eval_fold2_slist fll t tag
1129                             (loop (next t ctx) ctx rlist tag)
1130                             empty_res
1131
1132                 )
1133
1134               | `TAG(tag1),`TAG(tag2) -> (*OpCode.K5(fl_list,next,rlist,tag2,first,llist,tag1) *)
1135                   fun t ctx _ tag _ ->
1136                     eval_fold2_slist fll t tag
1137                       (loop_tag (next t ctx) ctx rlist tag2)
1138                       (loop_tag (first t) t llist tag1)
1139
1140               | `TAG(tag1),`ANY -> (* OpCode.K6(fl_list,next,rlist,first,llist,tag1) *)
1141                   fun t ctx _ tag _ ->
1142                     eval_fold2_slist fll t tag
1143                       (loop (next t ctx) ctx rlist tag)
1144                       (loop_tag (first t) t llist tag1)
1145
1146               | `ANY,`TAG(tag2) -> (* OpCode.K7(fl_list,next,rlist,tag2,first,llist) *)
1147                   fun t ctx _ tag _ ->
1148                     eval_fold2_slist fll t tag
1149                       (loop_tag (next t ctx) ctx rlist tag2)
1150                       (loop (first t) t llist tag)
1151
1152
1153               | _,_ -> (*OpCode.K8(fl_list,next,rlist,first,llist) *)
1154                   (*if SList.equal slist rlist && SList.equal slist llist
1155                     then
1156                     let rec loop t ctx =
1157                     if t == Tree.nil then empty_res else
1158                     let r1 = loop (first t) t
1159                     and r2 = loop (next t ctx) ctx
1160                     in
1161                     eval_fold2_slist fl_list t (Tree.tag tree t) r2 r1
1162                     in loop
1163                     else *)
1164                   fun t ctx _ tag _ ->
1165                     eval_fold2_slist fll t tag
1166                       (loop (next t ctx) ctx rlist tag)
1167                       (loop (first t) t llist tag)
1168
1169
1170
1171           in
1172           CodeCache.set_fun td_trans slist tag cont;
1173           cont t ctx slist tag noright
1174         in
1175         let _ = CodeCache.init mk_trans in
1176         (if noright then loop_no_right else loop) t ctx slist Tag.dummy
1177
1178
1179       let run_top_down a tree =
1180         let init = SList.cons a.init SList.nil in
1181         let _,res = top_down a tree Tree.root init Tree.root 1 (CodeCache.create BIG_A_SIZE) (Fold2Res.create 1024)
1182         in
1183         D_IGNORE_(
1184           output_trace a tree "trace.html"
1185             (RS.fold (fun t a -> IntSet.add (Tree.id tree t) a) res.(0) IntSet.empty),
1186               res.(0))
1187       ;;
1188
1189
1190
1191
1192
1193       module Code3Cache =
1194       struct
1195         let get = Array.get
1196         let set = Array.set
1197         let realloc a new_size default =
1198           let old_size = Array.length a in
1199           if old_size == new_size then a
1200           else if new_size == 0 then [||]
1201           else let na = Array.create new_size default in
1202           Array.blit a 0 na 0 old_size;na
1203
1204         type fun_tree = [`Tree] Tree.node -> [`Tree] Tree.node -> StateSet.t ->  Tag.t -> StateSet.t*RS.t
1205         and t = { mutable table : fun_tree array array;
1206                   mutable default_elm : fun_tree;
1207                   mutable default_line : fun_tree array;
1208                    (* statistics *)
1209                   mutable access : int;
1210                   mutable miss : int;
1211                  }
1212
1213
1214         let create () =
1215           { table = [||];
1216             default_elm = (fun _ _ _ _ -> failwith "Uninitialized Code3Cache.t structure\n");
1217             default_line = [||];
1218             access = 0;
1219             miss = 0 }
1220
1221         let init h f =
1222           let default_line = Array.create SMALL_A_SIZE f in
1223           begin
1224             h.table <- Array.create SMALL_A_SIZE default_line;
1225             h.default_elm <- f;
1226             h.default_line <- default_line;
1227             h.access <- 0;
1228             h.miss <- 0
1229           end
1230
1231         let next_power_of_2 n =
1232           let rec loop i acc =
1233             if acc == 0 then i
1234             else loop (i+1) (acc lsr 1)
1235           in
1236           1 lsl (loop 0 n)
1237
1238         let get_fun h slist tag =
1239           let _ = h.access <- h.access + 1 in
1240           let idx = Uid.to_int slist.StateSet.Node.id in
1241           let line =
1242             if idx >= Array.length h.table then
1243             let new_tab = realloc h.table (next_power_of_2 idx) h.default_line in
1244             let _ =  h.miss <- h.miss + 1; h.table <- new_tab in h.default_line
1245             else Array.unsafe_get h.table idx
1246           in
1247           if tag >= Array.length line then
1248           let new_line = realloc line (next_power_of_2 tag) h.default_elm in
1249           let _ = h.miss <- h.miss + 1; Array.unsafe_set h.table idx new_line in h.default_elm
1250           else Array.unsafe_get line tag
1251
1252         let set_fun (h : t) slist tag (data : fun_tree) =
1253           let idx = Uid.to_int slist.StateSet.Node.id in
1254           let line =
1255             if idx >= Array.length h.table then
1256             let new_tab = realloc h.table (next_power_of_2 idx) h.default_line in
1257             let _ =  h.table <- new_tab in h.default_line
1258             else Array.unsafe_get h.table idx
1259           in
1260           let line = if line == h.default_line then
1261           let l = Array.copy line in Array.unsafe_set h.table idx l;l
1262           else line in
1263           let line = if tag >= Array.length line then
1264           let new_line = realloc line (next_power_of_2 tag) h.default_elm in
1265           let _ = Array.unsafe_set h.table idx new_line in new_line
1266           else line
1267           in
1268           Array.unsafe_set line tag data
1269
1270
1271         let dump h = Array.iteri
1272           (fun id line -> if line != h.default_line then
1273            begin
1274              StateSet.print Format.err_formatter (StateSet.with_id (Uid.of_int id));
1275              Format.fprintf Format.err_formatter " -> ";
1276              Array.iteri (fun tag clos ->
1277                             if clos != h.default_elm then
1278                             Format.fprintf Format.err_formatter " (%s,%s) "
1279                               (Tag.to_string tag) (Trace.get_funname clos)) line;
1280              Format.fprintf Format.err_formatter "\n%!"
1281            end
1282           ) h.table;
1283           Format.fprintf Format.err_formatter "Cache hits: %i, Cache misses: %i, ratio = %f\n%!"
1284             h.access h.miss ((float_of_int h.miss)/. (float_of_int h.access));
1285           Format.fprintf Format.err_formatter "Size: %i kb\n%!"
1286             (((2+(Array.length h.default_line)+
1287                  (Array.fold_left (fun acc l ->acc + (if l == h.default_line then 0 else Array.length l))
1288                  (Array.length h.table) h.table)) * Sys.word_size) / 1024)
1289
1290       end
1291
1292       module StaticEnv =
1293       struct
1294
1295         type t = { stack : Obj.t array;
1296                    mutable top : int; }
1297
1298         let create () = { stack = Array.create BIG_A_SIZE (Obj.repr 0); top = 0 }
1299         let add t e =
1300           let _ = if t.top >= Array.length t.stack then failwith "Static Env overflow" in
1301           let i = t.top in Array.unsafe_set t.stack i e; t.top <- i + 1; i
1302
1303         let get t i :'a = Obj.magic (Array.unsafe_get t.stack i)
1304       end
1305
1306       module Fold3Res = struct
1307         let get = Array.unsafe_get
1308         let set = Array.set
1309         external field1 : Obj.t -> int = "%field1"
1310         type t = Obj.t array array array array
1311         let dummy_val = Obj.repr ((),2,())
1312
1313         let default_line3 = Array.create 1024 dummy_val
1314         let default_line2 = Array.create BIG_A_SIZE default_line3
1315         let default_line1 = Array.create BIG_A_SIZE default_line2
1316
1317         let create n = Array.create n default_line1
1318
1319         let find h tag fl s1 s2 : StateSet.t*bool*merge_conf =
1320           let l1 = get h (Uid.to_int fl.Formlist.Node.id) in
1321           let l2 = get l1 (Uid.to_int s1.StateSet.Node.id) in
1322           let l3 = get l2 (Uid.to_int s2.StateSet.Node.id) in
1323           Obj.magic (get l3 tag)
1324
1325         let is_valid b = b != (Obj.magic dummy_val)
1326         let get_replace tab idx default =
1327           let e = get tab idx in
1328           if e == default then
1329           let ne = Array.copy e in (set tab idx ne;ne)
1330           else e
1331
1332         let add h tag fl s1 s2 (data: StateSet.t*bool*merge_conf) =
1333           let l1 = get_replace h (Uid.to_int fl.Formlist.Node.id) default_line1 in
1334           let l2 = get_replace l1 (Uid.to_int s1.StateSet.Node.id) default_line2 in
1335           let l3 = get_replace l2 (Uid.to_int s2.StateSet.Node.id) default_line3 in
1336           set l3 tag (Obj.repr data)
1337       end
1338
1339
1340       let empty_res = StateSet.empty,RS.empty
1341
1342       let top_down1 a tree t slist ctx td_trans h_fold2  =
1343         (* evaluation starts from the right so we put sl1,res1 at the end *)
1344         let env = StaticEnv.create () in
1345         let slist_reg = ref StateSet.empty in
1346         let eval_fold2_slist fll t tag (sl2,res2) (sl1,res1) =
1347           let data = Fold3Res.find h_fold2 tag fll sl1 sl2  in
1348           if Fold3Res.is_valid data then
1349           let r,b,conf = data in
1350           (r,if b then RS.merge conf t res1 res2 else RS.empty)
1351           else
1352           let r,conf = eval_formlist tag sl1 sl2 fll in
1353           let b = conf <> NO in
1354           (Fold3Res.add h_fold2 tag fll sl1 sl2 (r,b,conf);
1355            (r, if b then RS.merge conf t res1 res2 else RS.empty))
1356
1357         in
1358         let loop t ctx slist _ =
1359           if t == Tree.nil then empty_res else
1360           let tag = Tree.tag tree t in
1361           (Code3Cache.get_fun td_trans slist tag) t ctx slist tag
1362
1363         in
1364         let loop_tag t ctx slist tag =
1365           if t == Tree.nil then empty_res else
1366           (Code3Cache.get_fun td_trans slist tag) t ctx slist tag
1367
1368         in
1369         let mk_trans t ctx slist tag =
1370           let fl_list,llist,rlist,ca,da,sa,fa =
1371             StateSet.fold
1372               (fun q acc ->
1373                  List.fold_left
1374                    (fun ((fl_acc,ll_acc,rl_acc,c_acc,d_acc,s_acc,f_acc) as acc)
1375                     (ts,t)  ->
1376                       if (TagSet.mem tag ts)
1377                       then
1378                       let _,_,_,f,_ = t.Transition.node in
1379                       let (child,desc,below),(sibl,foll,after) = Formula.st f in
1380                       (Formlist.cons t fl_acc,
1381                        StateSet.union ll_acc below,
1382                        StateSet.union rl_acc after,
1383                        StateSet.union child c_acc,
1384                        StateSet.union desc d_acc,
1385                        StateSet.union sibl s_acc,
1386                        StateSet.union foll f_acc)
1387                       else acc ) acc (
1388                      try Hashtbl.find a.trans q
1389                      with
1390                         Not_found -> Printf.eprintf "Looking for state %i, doesn't exist!!!\n%!"
1391                           q;[]
1392                    )
1393
1394               ) slist (Formlist.nil,StateSet.empty,StateSet.empty,
1395                        StateSet.empty,StateSet.empty,StateSet.empty,StateSet.empty)
1396
1397           in
1398           (* Logic to chose the first and next function *)
1399           let tags_child,tags_below,tags_siblings,tags_after = Tree.tags tree tag in
1400           let d_f = Algebra.decide a tags_child tags_below (StateSet.union ca da) true in
1401           let d_n = Algebra.decide a tags_siblings tags_after (StateSet.union sa fa) false in
1402           let f_kind,first = choose_jump_down tree d_f
1403           and n_kind,next = choose_jump_next tree d_n in
1404           let f_kind, first = `ANY, (Tree.first_element tree)
1405           and n_kind, next = `ANY, (Tree.next_element_below tree) in
1406           let cont =
1407             match f_kind,n_kind with
1408               | `NIL,`NIL ->
1409                   fun t _ _ tag -> eval_fold2_slist fl_list t tag empty_res empty_res
1410
1411               |  _,`NIL -> (
1412                    match f_kind with
1413                      |`TAG(tag1) ->
1414                         (fun t _ _ tag -> eval_fold2_slist fl_list t tag empty_res
1415                           (loop_tag (first t) t llist tag1))
1416                      | _ ->
1417                          fun t _ _ tag -> eval_fold2_slist fl_list t tag empty_res
1418                            (loop (first t) t llist tag)
1419                  )
1420               | `NIL,_ -> (
1421                   match n_kind with
1422                     |`TAG(tag2) ->
1423                        fun t ctx _ tag  ->
1424                          eval_fold2_slist fl_list t tag
1425                            (loop_tag (next t ctx) ctx rlist tag2)
1426                            empty_res
1427
1428                     | _ ->
1429                         fun t ctx _ tag ->
1430                           eval_fold2_slist fl_list t tag
1431                             (loop (next t ctx) ctx rlist tag)
1432                             empty_res
1433
1434                 )
1435
1436               | `TAG(tag1),`TAG(tag2) ->
1437                   fun t ctx _ tag ->
1438                     eval_fold2_slist fl_list t tag
1439                       (loop_tag (next t ctx) ctx rlist tag2)
1440                       (loop_tag (first t) t llist tag1)
1441
1442               | `TAG(tag1),`ANY ->
1443                   fun t ctx _ tag ->
1444                     eval_fold2_slist fl_list t tag
1445                       (loop (next t ctx) ctx rlist tag)
1446                       (loop_tag (first t) t llist tag1)
1447
1448               | `ANY,`TAG(tag2) ->
1449                   fun t ctx _ tag ->
1450                     eval_fold2_slist fl_list t tag
1451                       (loop_tag (next t ctx) ctx rlist tag2)
1452                       (loop (first t) t llist tag)
1453
1454
1455               | _,_ ->
1456                   fun t ctx _ tag ->
1457                     eval_fold2_slist fl_list t tag
1458                       (loop (next t ctx) ctx rlist tag)
1459                       (loop (first t) t llist tag)
1460
1461
1462
1463           in
1464           let _ = Trace.register_funname cont
1465             (Printf.sprintf "{first=%s, next=%s}" (Trace.get_funname first)  (Trace.get_funname next))
1466           in
1467           Code3Cache.set_fun td_trans slist tag cont;
1468           cont
1469         in
1470         let cache_take_trans t ctx slist tag =
1471           let cont = mk_trans t ctx slist tag in
1472           cont t ctx slist tag
1473         in
1474         Code3Cache.init td_trans (cache_take_trans);
1475         loop t ctx slist Tag.dummy
1476
1477
1478       let run_top_down1 a tree =
1479         let code_cache = Code3Cache.create ()  in
1480         let fold_cache = Fold3Res.create BIG_A_SIZE in
1481         let _,res = top_down1 a tree Tree.root a.init Tree.root code_cache fold_cache
1482         in
1483         Code3Cache.dump code_cache; 
1484         res
1485
1486
1487         module Configuration =
1488         struct
1489           module Ptss = Set.Make(StateSet)
1490           module IMap = Map.Make(StateSet)
1491           type t = { hash : int;
1492                         sets : Ptss.t;
1493                         results : RS.t IMap.t }
1494           let empty = { hash = 0;
1495                         sets = Ptss.empty;
1496                         results = IMap.empty;
1497                       }
1498           let is_empty c = Ptss.is_empty c.sets
1499           let add c s r =
1500             if Ptss.mem s c.sets then
1501               { c with results = IMap.add s (RS.concat r (IMap.find s c.results)) c.results}
1502             else
1503               { hash = HASHINT2(c.hash,Uid.to_int s.StateSet.Node.id);
1504                 sets = Ptss.add s c.sets;
1505                 results = IMap.add s r c.results
1506               }
1507
1508           let pr fmt c = Format.fprintf fmt "{";
1509             Ptss.iter (fun s -> StateSet.print fmt s;
1510                         Format.fprintf fmt "  ") c.sets;
1511             Format.fprintf fmt "}\n%!";
1512             IMap.iter (fun k d ->
1513                          StateSet.print fmt k;
1514                          Format.fprintf fmt "-> %i\n" (RS.length d)) c.results;
1515             Format.fprintf fmt "\n%!"
1516
1517           let merge c1 c2  =
1518             let acc1 =
1519               IMap.fold
1520                 ( fun s r acc ->
1521                     IMap.add s
1522                       (try
1523                          RS.concat r (IMap.find s acc)
1524                        with
1525                          | Not_found -> r) acc) c1.results IMap.empty
1526             in
1527             let imap =
1528                 IMap.fold (fun s r acc ->
1529                              IMap.add s
1530                                (try
1531                                   RS.concat r (IMap.find s acc)
1532                                 with
1533                                   | Not_found -> r) acc)  c2.results acc1
1534             in
1535             let h,s =
1536               Ptss.fold
1537                 (fun s (ah,ass) -> (HASHINT2(ah, Uid.to_int s.StateSet.Node.id ),
1538                                     Ptss.add s ass))
1539                 (Ptss.union c1.sets c2.sets) (0,Ptss.empty)
1540             in
1541               { hash = h;
1542                 sets =s;
1543                 results = imap }
1544
1545         end
1546
1547         let h_fold = Hashtbl.create 511
1548
1549         let fold_f_conf  tree t slist fl_list conf dir=
1550           let tag = Tree.tag tree t in
1551           let rec loop sl fl acc =
1552             match SList.node sl,fl with
1553               |SList.Nil,[] -> acc
1554               |SList.Cons(s,sll), formlist::fll ->
1555                  let r',mcnf =
1556                    let key = SList.hash sl,Formlist.hash formlist,dir in
1557                    try
1558                      Hashtbl.find h_fold key
1559                    with
1560                       Not_found -> let res =
1561                         if dir then eval_formlist tag s StateSet.empty formlist
1562                         else eval_formlist tag StateSet.empty s formlist
1563                       in (Hashtbl.add h_fold key res;res)
1564                  in
1565                  let (rb,rb1,rb2,mark) = bool_of_merge mcnf in
1566                  if rb && ((dir&&rb1)|| ((not dir) && rb2))
1567                  then
1568                  let acc =
1569                    let old_r =
1570                      try Configuration.IMap.find s conf.Configuration.results
1571                      with Not_found -> RS.empty
1572                    in
1573                    Configuration.add acc r' (if mark then RS.cons t old_r else old_r)
1574                  in
1575                  loop sll fll acc
1576                  else loop sll fll acc
1577               | _ -> assert false
1578           in
1579             loop slist fl_list Configuration.empty
1580
1581         let h_trans = Hashtbl.create 4096
1582
1583         let get_up_trans slist ptag a tree =
1584           let key = (HASHINT2(Uid.to_int slist.SList.Node.id ,ptag)) in
1585             try
1586           Hashtbl.find h_trans key
1587           with
1588           | Not_found ->
1589               let f_list =
1590                 Hashtbl.fold (fun q l acc ->
1591                                 List.fold_left (fun fl_acc (ts,t)  ->
1592                                                   if TagSet.mem ptag ts then Formlist.cons t fl_acc
1593                                                   else fl_acc)
1594
1595                                   acc l)
1596                   a.trans Formlist.nil
1597               in
1598               let res = SList.fold (fun _ acc -> f_list::acc) slist []
1599               in
1600                 (Hashtbl.add h_trans key res;res)
1601
1602
1603
1604         let h_tdconf = Hashtbl.create 511
1605         let rec bottom_up a tree t conf next jump_fun root dotd init accu =
1606           if (not dotd) && (Configuration.is_empty conf ) then
1607           accu,conf,next
1608           else
1609
1610           let below_right = Tree.is_below_right tree t next in
1611
1612           let accu,rightconf,next_of_next =
1613             if below_right then (* jump to the next *)
1614             bottom_up a tree next conf (jump_fun next) jump_fun (Tree.next_sibling tree t) true init accu
1615             else accu,Configuration.empty,next
1616           in
1617           let sub =
1618             if dotd then
1619             if below_right then prepare_topdown a tree t true
1620             else prepare_topdown a tree t false
1621             else conf
1622           in
1623           let conf,next =
1624             (Configuration.merge rightconf sub, next_of_next)
1625           in
1626           if t == root then  accu,conf,next else
1627           let parent = Tree.binary_parent tree t in
1628           let ptag = Tree.tag tree parent in
1629           let dir = Tree.is_left tree t in
1630           let slist = Configuration.Ptss.fold (fun e a -> SList.cons e a) conf.Configuration.sets SList.nil in
1631           let fl_list = get_up_trans slist ptag a parent in
1632           let slist = SList.rev (slist) in
1633           let newconf = fold_f_conf tree parent slist fl_list conf dir in
1634           let accu,newconf = Configuration.IMap.fold (fun s res (ar,nc) ->
1635                                                         if StateSet.intersect s init then
1636                                                           ( RS.concat res ar ,nc)
1637                                                         else (ar,Configuration.add nc s res))
1638             (newconf.Configuration.results) (accu,Configuration.empty)
1639           in
1640
1641             bottom_up a tree parent newconf next jump_fun root false init accu
1642
1643         and prepare_topdown a tree t noright =
1644           let tag = Tree.tag tree t in
1645           let r =
1646             try
1647               Hashtbl.find h_tdconf tag
1648             with
1649               | Not_found ->
1650                   let res = Hashtbl.fold (fun q l acc ->
1651                                             if List.exists (fun (ts,_) -> TagSet.mem tag ts) l
1652                                             then StateSet.add q acc
1653                                             else acc) a.trans StateSet.empty
1654                   in Hashtbl.add h_tdconf tag res;res
1655           in
1656 (*        let _ = pr ", among ";
1657             StateSet.print fmt (Ptset.Int.elements r);
1658             pr "\n%!";
1659           in *)
1660           let r = SList.cons r SList.nil in
1661           let set,res = top_down (~noright:noright) a tree t r t 1 (CodeCache.create BIG_A_SIZE) (Fold2Res.create 1024) in
1662           let set = match SList.node set with
1663             | SList.Cons(x,_) ->x
1664             | _ -> assert false
1665           in
1666           Configuration.add Configuration.empty set res.(0)
1667
1668
1669
1670         let run_bottom_up a tree k =
1671           let t = Tree.root in
1672           let trlist = Hashtbl.find a.trans (StateSet.choose a.init)
1673           in
1674           let init = List.fold_left
1675             (fun acc (_,t) ->
1676                let _,_,_,f,_ = Transition.node t in
1677                let _,_,l = fst ( Formula.st f ) in
1678                  StateSet.union acc l)
1679             StateSet.empty trlist
1680           in
1681           let tree1,jump_fun =
1682             match k with
1683               | `TAG (tag) ->
1684                   (*Tree.tagged_lowest t tag, fun tree -> Tree.tagged_next tree tag*)
1685                   (Tree.tagged_descendant tree tag t, let jump = Tree.tagged_following_below tree tag
1686                   in fun n -> jump n t )
1687               | `CONTAINS(_) -> (Tree.text_below tree t,let jump = Tree.text_next tree
1688                                  in fun n -> jump n t)
1689               | _ -> assert false
1690           in
1691           let tree2 = jump_fun tree1 in
1692           let rec loop t next acc =
1693             let acc,conf,next_of_next = bottom_up a tree t
1694               Configuration.empty next jump_fun (Tree.root) true init acc
1695             in
1696             let acc = Configuration.IMap.fold
1697               ( fun s res acc -> if StateSet.intersect init s
1698                 then RS.concat res acc else acc) conf.Configuration.results acc
1699             in
1700               if Tree.is_nil next_of_next  (*|| Tree.equal next next_of_next *)then
1701                 acc
1702               else loop next_of_next (jump_fun next_of_next) acc
1703           in
1704           loop tree1 tree2 RS.empty
1705
1706
1707     end
1708
1709     let top_down_count a t = let module RI = Run(Integer) in Integer.length (RI.run_top_down a t)
1710     let top_down_count1 a t = let module RI = Run(Integer) in Integer.length (RI.run_top_down1 a t)
1711     let top_down a t = let module RI = Run(IdSet) in (RI.run_top_down a t)
1712     let top_down1 a t = let module RI = Run(IdSet) in (RI.run_top_down1 a t)
1713     let bottom_up_count a t k = let module RI = Run(Integer) in Integer.length (RI.run_bottom_up a t k)
1714     let bottom_up a t k = let module RI = Run(IdSet) in (RI.run_bottom_up a t k)
1715
1716     module Test (Doc : sig val doc : Tree.t end) =
1717       struct
1718         module Results = GResult(Doc)
1719         let top_down a t = let module R = Run(Results) in (R.run_top_down a t)
1720         let top_down1 a t = let module R = Run(Results) in (R.run_top_down1 a t)
1721       end
1722