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