Fix stupid bug with Tag indices
[SXSI/xpathcomp.git] / tree.ml
1 (******************************************************************************)
2 (*  SXSI : XPath evaluator                                                    *)
3 (*  Kim Nguyen (Kim.Nguyen@nicta.com.au)                                      *)
4 (*  Copyright NICTA 2008                                                      *)
5 (*  Distributed under the terms of the LGPL (see LICENCE)                     *)
6 (******************************************************************************)
7 module type BINARY =
8 sig
9   type node_content
10   type string_content
11   type descr = Nil | Node of node_content  |String of string_content 
12   type t
13   val parse_xml_uri : string -> t
14   val parse_xml_string : string -> t
15   val tag_pool : t -> Tag.pool
16   val string : t -> string
17   val descr : t -> descr
18   val left : t -> t
19   val right : t -> t
20   val parent : t -> t
21   val id : t -> int
22   val tag : t -> Tag.t
23   val print_xml_fast : out_channel -> t -> unit
24   val compare : t -> t -> int
25   val equal : t -> t -> bool
26   module DocIdSet : Set.S with type elt = string_content
27   val string_below : t -> string_content -> bool
28   val contains : t -> string -> DocIdSet.t
29   val contains_old : t -> string -> bool
30   val dump : t -> unit
31 end
32
33 module XML = 
34 struct
35
36   type t
37   type 'a node = int
38   type node_kind = [`Text | `Tree ]
39
40   let compare : 'a node -> 'a node -> int = (-)
41   let equal : 'a node -> 'a node -> bool = (==)
42
43         (* abstract type, values are pointers to a XMLTree C++ object *)
44     
45   external int_of_node : 'a node -> int = "%identity"
46
47   external parse_xml_uri : string  -> t = "caml_call_shredder_uri"
48   let parse_xml_uri uri = parse_xml_uri uri
49     
50   external parse_xml_string :  string  -> t = "caml_call_shredder_string"
51   let parse_xml_string uri = parse_xml_string uri
52     
53
54   module Text =
55   struct
56
57     (* Todo *)
58     external nullt : unit -> [`Text ] node = "caml_xml_tree_nullt"
59     let nil = nullt ()
60     external get_text : t -> [`Text] node -> string = "caml_text_collection_get_text"
61
62     let get_text t n = 
63       if equal nil n then "" 
64       else  get_text t n
65                 
66     external is_empty : t -> [`Text ] node -> bool = "caml_text_collection_empty_text"
67     let is_empty t n =
68       (equal nil n) || is_empty t n
69
70     external is_contains : t -> string -> bool = "caml_text_collection_is_contains"
71     external count_contains : t -> string -> int = "caml_text_collection_count_contains"
72     external contains : t -> string -> [`Text ] node array = "caml_text_collection_contains"
73   end
74
75
76   module Tree = 
77   struct
78
79       
80     external serialize : t -> string -> unit = "caml_xml_tree_serialize"
81     external unserialize : string -> t = "caml_xml_tree_unserialize"
82       
83     external root : t -> [`Tree] node = "caml_xml_tree_root"
84     external nullt : unit -> [`Tree ] node = "caml_xml_tree_nullt"
85
86     let nil = nullt ()
87     let is_nil x = equal x nil
88
89     external parent : t -> [`Tree] node -> [`Tree] node = "caml_xml_tree_parent"
90     external parent_doc : t -> [`Text ] node -> [`Tree ] node = "caml_xml_tree_parent_doc"
91     external first_child : t -> [`Tree] node -> [`Tree] node = "caml_xml_tree_first_child"
92       
93
94       
95     external next_sibling : t -> [`Tree] node -> [`Tree] node = "caml_xml_tree_next_sibling"
96
97     external is_leaf : t  -> [`Tree] node -> bool = "caml_xml_tree_is_leaf"
98     
99 (*    external tag : t -> [`Tree ] node -> T = "caml_xml_tree_tag"*)
100     external tag_id : t -> [`Tree ] node -> Tag.t = "caml_xml_tree_tag_id"
101
102     let is_last t n = equal nil (next_sibling t n)
103     
104     external prev_text : t -> [`Tree] node -> [`Text ] node = "caml_xml_tree_prev_text" 
105
106
107     external my_text : t -> [`Tree] node -> [`Text ] node = "caml_xml_tree_my_text"
108     external next_text : t -> [`Tree] node -> [`Text ] node = "caml_xml_tree_next_text"
109
110     external text_xml_id : t -> [`Text ] node -> int = "caml_xml_tree_text_xml_id"
111     external node_xml_id : t -> [`Tree ] node -> int = "caml_xml_tree_node_xml_id"
112     external is_ancestor : t -> [`Tree ] node -> [`Tree ] node -> bool = "caml_xml_tree_is_ancestor"
113
114     let print_skel t =
115       let rec aux id = 
116         if (is_nil id)
117         then Printf.eprintf "#\n"
118         else 
119           begin
120             Printf.eprintf "Node %i has tag '%s' DocOrder=%i, DocID of PrevText,MyText,NextText : (%i = %s,%i = %s,%i = %s)\n%!" 
121               (int_of_node id)
122               (Tag.to_string (tag_id t id))
123               (node_xml_id t id)
124               (int_of_node (prev_text t id))
125               (Text.get_text t (prev_text t id))
126               (int_of_node (my_text t id))
127               (Text.get_text t (my_text t id))
128               (int_of_node (next_text t id))
129               (Text.get_text t (next_text t id));
130             aux(first_child t id);
131             aux(next_sibling t id);
132           end
133       in
134         aux (root t)
135
136     let traversal t = 
137         let rec aux id =
138           if not (is_nil id)
139           then
140             begin
141               (* ignore (tag t id);
142               ignore (Text.get_text t (prev_text t id));
143               if (is_leaf t id)
144                 then ignore (Text.get_text t (my_text t id));
145               if (is_last t id)
146                 then ignore (Text.get_text t (next_text t id)); *)
147               aux (first_child t id);
148               aux (next_sibling t id);
149             end
150         in
151           aux (root t)
152   end
153       
154       
155   module Binary  = struct
156
157     type node_content = 
158         NC of [`Tree ] node 
159       | SC of [`Text ] node * [`Tree ] node 
160     type string_content = [ `Text ] node
161     type descr = 
162       | Nil 
163       | Node of node_content
164       | String of string_content
165
166     type doc = t
167
168     type t = { doc : doc;              
169                node : descr }
170         
171     let dump { doc=t } = Tree.print_skel t
172     module DocIdSet = Set.Make (struct type t = string_content
173                                        let compare = (-) end)
174       
175
176     open Tree                  
177     let node_of_t t = { doc= t; 
178                         node = Node(NC (root t)) }
179
180
181     let parse_xml_uri str = node_of_t (parse_xml_uri str)
182     let parse_xml_string str = node_of_t (parse_xml_string str)
183
184
185     external pool : doc -> Tag.pool = "%identity"
186     let tag_pool t = pool t.doc
187
188     let compare a b = match a.node,b.node  with
189       | Node(NC i),Node(NC j) -> compare i j
190       | _, Node(NC( _ )) -> 1
191       | Node(SC (i,_)),Node(SC (j,_)) -> compare i j
192       | Node(NC( _ )),Node(SC (_,_)) -> -1
193       | _, Node(SC (_,_)) -> 1
194       | String i, String j -> compare i j
195       | Node _ , String _ -> -1
196       | _ , String _ -> 1
197       | Nil, Nil -> 0
198       | _,Nil -> -1
199
200     let equal a b = (compare a b) == 0
201
202     let string t = match t.node with
203       | String i ->  Text.get_text t.doc i
204       | _ -> assert false
205           
206     let norm (n : [`Tree ] node ) =  if is_nil n then Nil else Node (NC n)
207         
208     let descr t = t.node
209
210     let nts = function
211         Nil -> "Nil"
212       | String i -> Printf.sprintf "String %i" i
213       | Node (NC t) -> Printf.sprintf "Node (NC %i)"  (int_of_node t)
214       | Node (SC (t,i)) -> Printf.sprintf "Node (SC (%i,%i))"  (int_of_node t) (int_of_node i)
215
216
217     let parent n = 
218       let node' =
219         match n.node with
220           | Node(NC t) | Node(SC (_,t)) -> 
221               if (Tree.root n.doc) == t
222               then Nil
223               else Node(NC(Tree.parent n.doc t)) (* A parent node can never be a SC *)
224           | _ -> assert false
225       in
226         { n with node = node' }
227
228     let first_child n = 
229       let node' = 
230         match n.node with
231           | Node (NC t) when is_leaf n.doc t ->
232               let txt = my_text n.doc t in
233                 if Text.is_empty n.doc txt
234                 then Nil
235                 else Node(SC (txt,Tree.nil))
236           | Node (NC t) -> 
237               let fs = first_child n.doc t in
238               let txt = prev_text n.doc fs in
239                 if Text.is_empty n.doc txt
240                 then norm fs
241                 else Node (SC (txt, fs))                  
242           | Node(SC (i,_)) -> String i
243           | Nil | String _ -> failwith "first_child"
244       in
245         { n with node = node'}
246
247           
248     let next_sibling n = 
249       let node' =
250         match n.node with
251           | Node (SC (_,ns)) -> norm ns
252           | Node(NC t) ->
253               let ns = next_sibling n.doc t in
254               let txt = next_text n.doc t in
255                 if Text.is_empty n.doc txt
256                 then norm ns
257                 else Node (SC (txt, ns))
258           | Nil | String _  -> failwith "next_sibling"
259       in
260         { n with node = node'}
261           
262           
263     let left = first_child 
264     let right = next_sibling
265     
266     let id = 
267       function  { doc=d; node=Node(NC n)}  -> node_xml_id d n
268         | { doc=d;  node=Node(SC (i,_) )} -> text_xml_id d i
269         | _ -> failwith "id"
270             
271     let tag = 
272       function { node=Node(SC _) } -> Tag.pcdata
273         | { doc=d; node=Node(NC n)} -> tag_id d n
274         | _ -> failwith "tag"
275     
276 (*    let tag_id = 
277       function  { node=Node(SC _) } -> ()
278         | { doc=d; node=Node(NC n)} -> tag_id d n
279         | _ -> ()
280 *)
281     let string_below t id =
282       let pid = parent_doc t.doc id in
283         match t.node with
284           | Node(NC(i)) -> (is_ancestor t.doc i pid)
285           | Node(SC(i,_)) -> (is_ancestor t.doc (parent_doc t.doc i) pid)
286           | _ -> false
287               
288     let contains t s = 
289       Array.fold_left (fun a i -> DocIdSet.add i a) DocIdSet.empty (Text.contains t.doc s)
290
291     let contains_old t s = 
292       let regexp = Str.regexp_string s in
293       let matching arg = 
294         try
295           let _ = Str.search_forward regexp arg 0;
296           in true
297         with _ -> false
298       in
299       let rec find t = match t.node with
300         | Nil -> false
301         | String _ -> matching (string t)
302         | Node(_) -> (find (left t )) || (find (right t)) 
303       in
304         find t 
305
306     let print_xml_fast outc t =
307       let rec loop ?(print_right=true) t = match t.node with 
308         | Nil -> ()
309         | String (s) -> output_string outc (string t)
310         | Node _ when Tag.equal (tag t) Tag.pcdata -> loop (left t); loop (right t)
311             
312         | Node (_) -> 
313             let tg = Tag.to_string (tag t) in
314             let l = left t 
315             and r = right t 
316             in
317               output_char outc  '<';
318               output_string outc  tg;
319               ( match l.node with
320                     Nil -> output_string outc  "/>"
321                   | String _ -> assert false
322                   | Node(_) when Tag.equal (tag l) Tag.attribute -> 
323                       (loop_attributes (left l);
324                        match (right l).node with
325                          | Nil -> output_string outc  "/>"
326                          | _ -> 
327                              output_char outc  '>'; 
328                              loop (right l);
329                              output_string outc  "</";
330                              output_string outc  tg;
331                              output_char outc '>' )
332                   | _ ->
333                       output_char outc  '>'; 
334                       loop l;
335                       output_string outc "</";
336                       output_string outc tg;
337                       output_char outc '>'
338               );if print_right then loop r
339       and loop_attributes a =
340
341         match a.node with 
342           | Node(_) ->
343               let value =
344                 match (left a).node with
345                   | Nil -> ""
346                   | _ -> string (left(left a)) 
347               in
348                 output_char outc ' ';
349                 output_string outc (Tag.to_string (tag a));
350                 output_string outc "=\"";
351                 output_string outc value;
352                 output_char outc '"';
353                 loop_attributes (right a)
354         | _ -> ()
355       in
356         loop ~print_right:false t
357
358
359     let print_xml_fast outc t = 
360       if Tag.to_string (tag t) = "" then
361         print_xml_fast outc (first_child t)
362       else print_xml_fast outc t
363         
364     let traversal t = Tree.traversal t.doc
365     let full_traversal t = 
366       let rec aux n =
367         match n.node with
368         | Nil -> ()
369         | String i -> () (*ignore(Text.get_text t.doc i)  *)
370         | Node(_) -> 
371             (* tag_id n; *)
372             aux (first_child n);
373             aux (next_sibling n)
374       in aux t
375   end
376
377 end
378
379
380
381
382
383 module DEBUGTREE 
384   = struct
385     
386     let _timings = Hashtbl.create 107
387     
388
389     let time _ref f arg = 
390       let t1 = Unix.gettimeofday () in
391       let r = f arg in
392       let t2 = Unix.gettimeofday () in 
393       let t = (1000. *.(t2 -. t1)) in
394
395       let (time,count) = try 
396         Hashtbl.find _timings _ref
397       with
398         | Not_found -> 0.,0
399       in
400       let time = time+. t 
401       and count = count + 1
402       in
403         Hashtbl.replace _timings _ref (time,count);r
404
405     include XML.Binary
406
407
408     let first_child_ doc node = 
409      time ("XMLTree.FirstChild()") (XML.Tree.first_child doc)  node
410     let next_sibling_ doc node = 
411       time ("XMLTree.NextSibling()") (XML.Tree.next_sibling doc) node
412
413     let is_empty_ text node = 
414       time ("TextCollection.IsEmpty()") (XML.Text.is_empty text) node
415
416     let prev_text_ doc node = 
417       time ("XMLTree.PrevText()") (XML.Tree.prev_text doc) node
418
419     let my_text_ doc node = 
420       time ("XMLTree.MyText()") (XML.Tree.my_text doc) node
421         
422     let next_text_ doc node = 
423       time ("XMLTree.NextText()") (XML.Tree.next_text doc) node
424
425     let is_leaf_ doc node =  
426       time ("XMLTree.IsLeaf()") (XML.Tree.is_leaf doc ) node
427         
428     let node_xml_id_ doc node =  
429       time ("XMLTree.NodeXMLId()") (XML.Tree.node_xml_id doc ) node
430         
431     let text_xml_id_ doc node =  
432       time ("XMLTree.TextXMLId()") (XML.Tree.text_xml_id doc ) node
433
434
435     let first_child n =
436       let node' =
437         match n.node with
438           | Node (NC t) when is_leaf_ n.doc t ->
439               let txt = my_text_ n.doc t in
440                 if is_empty_ n.doc txt
441                 then Nil
442                 else Node(SC (txt,XML.Tree.nil))
443           | Node (NC t) ->
444               let fs = first_child_ n.doc t in
445               let txt = prev_text_ n.doc fs in
446                 if is_empty_ n.doc txt
447                 then norm fs
448                 else Node (SC (txt, fs))
449           | Node(SC (i,_)) -> String i
450           | Nil | String _ -> failwith "first_child"
451       in
452         { n with node = node'}
453
454           
455     let next_sibling n =
456       let node' =
457         match n.node with
458           | Node (SC (_,ns)) -> norm ns
459           | Node(NC t) ->
460               let ns = next_sibling_ n.doc t in
461               let txt = 
462                 if XML.Tree.is_nil ns then
463                   next_text_ n.doc t 
464                 else prev_text_ n.doc ns
465               in
466                 if is_empty_ n.doc txt
467                 then norm ns
468                 else Node (SC (txt, ns))
469           | Nil | String _  -> failwith "next_sibling"
470       in
471         { n with node = node'}
472
473     let id = 
474       function  { doc=d; node=Node(NC n)}  -> node_xml_id_ d n
475         | { doc=d;  node=Node(SC (i,_) )} -> text_xml_id_ d i
476         | _ -> failwith "id"
477             
478     (* Wrapper around critical function *)
479     let string t = time ("TextCollection.GetText()") (string) t
480     let left = first_child
481     let right = next_sibling
482     let tag t =  time ("XMLTree.GetTag()") (tag) t
483       
484     let print_stats ppf = 
485       let total_time,total_calls =
486         Hashtbl.fold  (fun _ (t,c) (tacc,cacc) ->
487                          tacc+. t, cacc + c)  _timings (0.,0)
488
489       in
490         Format.fprintf ppf
491           "Timing : Function Name, number of calls,%% of total calls, mean time, total time, %% of total time\n%!";
492         Hashtbl.iter (fun name (time,count) ->
493                         Format.fprintf ppf  "%-27s% 8d\t% 4.2f%%\t% 4.6f ms\t% 4.6f ms\t%04.2f%%\n%!"
494                           name 
495                           count 
496                           (100. *. (float_of_int count)/.(float_of_int total_calls))
497                           (time /. (float_of_int count))
498                           time
499                           (100. *. time /.  total_time)) _timings;
500         Format.fprintf ppf  "-------------------------------------------------------------------\n";
501         Format.fprintf ppf "%-27s% 8d\t% 4.0f%%\t########## ms\t% 4.6f ms\t% 4.0f%%\n%!"
502           "Total" total_calls 100. total_time 100.
503                           
504
505     let print_xml_fast outc t =
506       let rec loop ?(print_right=true) t = match t.node with 
507         | Nil -> ()
508         | String (s) -> output_string outc (string t)
509         | Node _ when Tag.equal (tag t) Tag.pcdata -> loop (left t); loop (right t)
510             
511         | Node (_) -> 
512             let tg = Tag.to_string (tag t) in
513             let l = left t 
514             and r = right t 
515             in
516               output_char outc  '<';
517               output_string outc  tg;
518               ( match l.node with
519                     Nil -> output_string outc  "/>"
520                   | String _ -> assert false
521                   | Node(_) when Tag.equal (tag l) Tag.attribute -> 
522                       (loop_attributes (left l);
523                        match (right l).node with
524                          | Nil -> output_string outc  "/>"
525                          | _ -> 
526                              output_char outc  '>'; 
527                              loop (right l);
528                              output_string outc  "</";
529                              output_string outc  tg;
530                              output_char outc '>' )
531                   | _ ->
532                       output_char outc  '>'; 
533                       loop l;
534                       output_string outc "</";
535                       output_string outc tg;
536                       output_char outc '>'
537               );if print_right then loop r
538       and loop_attributes a =
539
540         match a.node with 
541           | Node(_) ->
542               let value =
543                 match (left a).node with
544                   | Nil -> ""
545                   | _ -> string (left(left a)) 
546               in
547                 output_char outc ' ';
548                 output_string outc (Tag.to_string (tag a));
549                 output_string outc "=\"";
550                 output_string outc value;
551                 output_char outc '"';
552                 loop_attributes (right a)
553         | _ -> ()
554       in
555         loop ~print_right:false t
556
557
558     let print_xml_fast outc t = 
559       if Tag.to_string (tag t) = "" then
560         print_xml_fast outc (first_child t)
561       else print_xml_fast outc t
562
563         
564
565
566 end
567
568 module Binary = DEBUGTREE