Split the Options module in two to remove a circular dependency in
[SXSI/xpathcomp.git] / src / 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 INCLUDE "debug.ml"
8 INCLUDE "log.ml"
9 INCLUDE "utils.ml"
10
11 external init_lib : unit -> unit = "sxsi_cpp_init"
12
13 exception CPlusPlusError of string
14
15 let () = Callback.register_exception "CPlusPlusError" (CPlusPlusError "")
16
17 let () =  init_lib ()
18
19 type node = [ `Tree ] Node.t
20
21 type tree
22
23 external register_tag : tree -> string -> Tag.t = "caml_xml_tree_register_tag"
24
25 external tag_name : tree -> Tag.t -> string = "caml_xml_tree_get_tag_name"
26
27 let tag t = (); fun s ->
28   match s with
29   | "<$>" -> Tag.pcdata
30   | "<@>" -> Tag.attribute
31   | "" -> Tag.document_node
32   | "<@$>" -> Tag.attribute_data
33   | _ -> register_tag t s
34
35 let to_string d = ();
36   fun t ->
37     if t == Tag.pcdata then "<$>"
38     else if t == Tag.attribute_data then "<@$>"
39     else if t == Tag.attribute then "<@>"
40     else if t == Tag.nullt then "<!NIL!>"
41     else tag_name d t
42
43 let translate  x = x
44
45 let mk_tag_ops t = {
46   Tag.tag = tag t;
47   Tag.to_string = to_string t;
48   Tag.translate = translate
49 }
50
51 module TreeBuilder =
52 struct
53   type t
54   external create : unit -> t = "caml_xml_tree_builder_create"
55   external open_document : t -> int -> bool -> int -> unit = "caml_xml_tree_builder_open_document"
56   external close_document : t -> tree = "caml_xml_tree_builder_close_document"
57   external open_tag : t -> string -> unit = "caml_xml_tree_builder_open_tag"
58   external close_tag : t -> string -> unit = "caml_xml_tree_builder_close_tag"
59   external text : t -> string -> unit = "caml_xml_tree_builder_text"
60   external trim : string -> string = "caml_trim"
61
62   let is_whitespace s =
63     let rec loop len i =
64       if i < len then
65         let c = s.[i] in
66         (c == '\n' || c == '\t' || c == ' ') && loop len (i+1)
67       else
68         true
69     in
70     loop (String.length s) 0
71
72
73   let display_count =
74     let event_counter = ref 0 in
75     (fun parser_ ->
76       incr event_counter;
77       if !event_counter land 0xffffff == 0 then
78         Logger.print Format.err_formatter "Current position: %i@\n@?" (Expat.get_current_byte_index parser_))
79
80
81   let do_text b t =
82     if Buffer.length t > 0 then begin
83       let s = Buffer.contents t in
84       if (!Config.index_empty_texts) || not (is_whitespace s) then
85         begin
86           open_tag b "<$>";
87           text b s;
88           close_tag b "<$>";
89         end;
90       Buffer.clear t
91     end
92
93   let output_attr b name value =
94     let atname = "<@>" ^ name in
95     open_tag b atname;
96     open_tag b "<@$>";
97     text b value;
98     close_tag b "<@$>";
99     close_tag b atname
100
101   let start_element_handler parser_ b t tag attr_list =
102     do_text b t;
103     open_tag b tag;
104     match attr_list with
105       [] -> ()
106     | l ->
107       open_tag b "<@>";
108       List.iter (fun (name, value) -> output_attr b name value) l;
109       close_tag b "<@>"
110
111
112   let end_element_handler parser_ b t tag =
113     do_text b t;
114     close_tag b tag
115
116   let character_data_handler parser_ _ t text =
117     Buffer.add_string t text
118
119   let create_parser () =
120     let buf = Buffer.create 512 in
121     let build = create () in
122     let parser_ = Expat.parser_create ~encoding:None in
123     let finalize () =
124       do_text build buf;
125       close_tag build "";
126       LOG ( __ "parsing" 2 "%s\n" "Finished parsing");
127       LOG ( __ "indexing" 2 "%s\n" "Starting index construction");
128       let r = close_document build in
129       LOG ( __ "indexing" 2 "%s\n" "Finished index construction");
130       r
131     in
132     Expat.set_start_element_handler parser_ (start_element_handler parser_ build buf);
133     Expat.set_end_element_handler parser_ (end_element_handler parser_ build buf);
134     Expat.set_character_data_handler parser_ (character_data_handler parser_ build buf);
135     LOG ( __ "parsing" 2 "%s\n" "Started parsing");
136     open_document build !Config.sample_factor !Config.disable_text_collection !Config.text_index_type;
137     open_tag build "";
138     parser_, finalize
139
140   let parse_string s =
141     let parser_, finalizer = create_parser () in
142     Expat.parse parser_ s;
143     finalizer ()
144
145   let parse_file file =
146     let in_chan = open_in file in
147     let buffer = String.create 4096 in
148     let parser_, finalizer = create_parser () in
149     let () =
150       try
151         while true do
152           let read = input in_chan buffer 0 4096 in
153           if read == 0 then raise End_of_file else
154             Expat.parse_sub parser_ buffer 0 read;
155         done
156
157       with
158       | End_of_file -> close_in in_chan
159       | e -> raise e
160     in
161     finalizer ()
162
163 end
164
165
166
167
168 type bit_vector = string
169
170 external bool_of_int : int -> bool = "%identity"
171 external int_of_bool : bool -> int = "%identity"
172
173 let bit_vector_unsafe_get v i =
174   bool_of_int
175     (((Char.code (String.unsafe_get v (i lsr 3))) lsr (i land 7)) land 1)
176 let chr (c:int) : char = Obj.magic (c land 0xff)
177 let bit_vector_unsafe_set v i b =
178   let j = i lsr 3 in
179   let c = Char.code v.[j] in
180   let bit = int_of_bool b in
181   let mask = bit lsl (i land 7) in
182   if b then v.[j] <- chr (c lor mask) else v.[j] <- (chr (c land (lnot mask)))
183
184 let bit_vector_create n =
185   let len = if n <= 0 then 0 else (n - 1) / 8 + 1 in
186   String.make len '\000'
187
188 type tag_list
189
190 external tag_list_alloc : int -> tag_list = "caml_tag_list_alloc"
191 external tag_list_set : tag_list -> int -> Tag.t -> unit = "caml_tag_list_set" "noalloc"
192
193 type t = {
194   doc : tree;
195   elements: Ptset.Int.t;
196   attributes: Ptset.Int.t;
197   attribute_array : tag_list;
198   children : Ptset.Int.t array;
199   siblings : Ptset.Int.t array;
200   descendants: Ptset.Int.t array;
201   followings: Ptset.Int.t array;
202 }
203
204
205 let tag_operations t = mk_tag_ops t.doc
206 (*
207   external parse_xml_uri : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_uri"
208   external parse_xml_string :  string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_string"
209 *)
210 external tree_print_xml_fast3 : tree -> [`Tree ] Node.t -> Unix.file_descr -> unit = "caml_xml_tree_print"
211 let print_xml t n fd =
212   tree_print_xml_fast3 t.doc n fd
213
214
215 external tree_save : tree -> Unix.file_descr -> string -> unit = "caml_xml_tree_save"
216 external tree_load : Unix.file_descr -> string -> bool -> int -> tree = "caml_xml_tree_load"
217
218 external nullt : unit -> 'a Node.t = "caml_xml_tree_nullt"
219
220 let nil : [`Tree ] Node.t = Node.nil
221 let root : [`Tree ] Node.t = Node.null
222
223
224 module HPtset = Hashtbl.Make(Ptset.Int)
225
226 let vector_htbl = HPtset.create MED_H_SIZE
227 let reinit () = HPtset.clear vector_htbl
228
229 let tag_list_of_set s =
230   try
231     HPtset.find vector_htbl s
232   with
233     Not_found ->
234       let v = tag_list_alloc (Ptset.Int.cardinal s + 1) in
235       let i = ref 0 in
236       let () = Ptset.Int.iter (fun e -> tag_list_set v !i e; incr i) s in
237       let () = tag_list_set v !i Tag.nullt in
238       HPtset.add vector_htbl s v; v
239
240 (** tree interface *)
241
242 external tree_root : tree -> [`Tree] Node.t = "caml_xml_tree_root"  "noalloc"
243
244
245 external tree_first_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_child" "noalloc"
246 let first_child t n = tree_first_child t.doc n
247
248 external tree_first_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_element" "noalloc"
249 let first_element t n = tree_first_element t.doc n
250
251 external tree_tagged_child : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_child" "noalloc"
252 let tagged_child t n tag = tree_tagged_child t.doc n tag
253
254 external tree_select_child : tree -> [`Tree ] Node.t -> tag_list -> [`Tree] Node.t = "caml_xml_tree_select_child" "noalloc"
255 let select_child t n tag_set = tree_select_child t.doc n tag_set
256
257 external tree_last_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_last_child" "noalloc"
258 let last_child t n = tree_last_child t.doc n
259
260
261 external tree_next_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_sibling"  "noalloc"
262 let next_sibling t n = tree_next_sibling t.doc n
263
264 external tree_next_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_element"  "noalloc"
265 let next_element t n = tree_next_element t.doc n
266
267
268 external tree_tagged_sibling : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_sibling" "noalloc"
269 let tagged_sibling t n tag = tree_tagged_sibling t.doc n tag
270
271
272 external tree_select_sibling : tree -> [`Tree ] Node.t -> tag_list -> [`Tree] Node.t = "caml_xml_tree_select_sibling" "noalloc"
273 let select_sibling t n tag_set = tree_select_sibling t.doc n tag_set
274
275 external tree_prev_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_prev_sibling" "noalloc"
276 let prev_sibling t n = tree_prev_sibling t.doc n
277
278
279
280 external tree_tagged_descendant : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_descendant" "noalloc"
281 let tagged_descendant t n tag = tree_tagged_descendant t.doc n tag
282
283 external tree_tagged_next : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_next" "noalloc"
284 let tagged_next t n tag = tree_tagged_next t.doc n tag
285
286 external tree_select_descendant : tree -> [`Tree ] Node.t -> tag_list -> [`Tree] Node.t = "caml_xml_tree_select_descendant" "noalloc"
287 let select_descendant t n tag_set = tree_select_descendant t.doc n tag_set
288
289 external tree_tagged_following_before : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_following_before" "noalloc"
290 let tagged_following_before t n tag ctx = tree_tagged_following_before t.doc n tag ctx
291
292 external tree_select_following_before : tree -> [`Tree ] Node.t -> tag_list -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_select_following_before" "noalloc"
293 let select_following_before t n tag_set ctx = tree_select_following_before t.doc n tag_set ctx
294
295 external tree_parent : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_parent" "noalloc"
296 let parent t n = tree_parent t.doc n
297
298 external tree_tag : tree -> [`Tree] Node.t -> Tag.t = "caml_xml_tree_tag" "noalloc"
299 let tag t n = tree_tag t.doc n
300
301 external tree_is_first_child : tree -> [ `Tree ] Node.t -> bool = "caml_xml_tree_is_first_child" "noalloc"
302 let is_first_child t n = tree_is_first_child t.doc n
303
304 external tree_is_right_descendant : tree -> [ `Tree ] Node.t -> [`Tree] Node.t -> bool =
305   "caml_xml_tree_is_right_descendant" "noalloc"
306
307 let is_right_descendant t n1 n2 = tree_is_right_descendant t.doc n1 n2
308 ;;
309
310 let node_tags t = Ptset.Int.add Tag.document_node t.descendants.(Tag.document_node)
311
312 let attribute_tags t = t.attributes
313
314 let element_tags t = t.elements
315
316 let tags t tag =
317   t.children.(tag), t.descendants.(tag), t.siblings.(tag), t.followings.(tag)
318
319 open Format
320 let dump_tag_table t =
321   let tag = ref 0 in
322   let printer ppf set =
323     Logger.print ppf "%s: %a"
324       (Tag.to_string !tag) TagSet.print (TagSet.inj_positive set);
325     incr tag
326   in
327   let set_printer msg set =
328     tag := 0;
329     Logger.print err_formatter "%s :@\n" msg;
330     Pretty.pp_print_array ~sep:pp_force_newline printer err_formatter set;
331     Logger.print err_formatter "-----------------------------@\n";
332   in
333   set_printer "Child tags" t.children;
334   set_printer "Descendant tags" t.descendants;
335   set_printer "Sibling tags" t.siblings;
336   set_printer "Following tags" t.followings
337
338 external tree_subtree_tags : tree -> [`Tree] Node.t -> Tag.t -> int = "caml_xml_tree_subtree_tags" "noalloc"
339 let subtree_tags t n tag = tree_subtree_tags t.doc n tag
340
341 external tree_subtree_size : tree -> [`Tree] Node.t -> int = "caml_xml_tree_subtree_size" "noalloc"
342 let subtree_size t n = tree_subtree_size t.doc n
343
344 let rec iter_array_tag i a len tree node acc =
345   if i == len then acc
346   else
347     iter_array_tag (i+1) a len tree node
348       (acc - (tree_subtree_tags tree node a.(i)))
349
350 external tree_subtree_elements : tree -> [`Tree] Node.t -> int = "caml_xml_tree_subtree_elements" "noalloc"
351
352 let subtree_elements t node =
353   tree_subtree_elements t.doc node
354 (*
355 let subtree_elements t node =
356   let size = tree_subtree_size t.doc node - 1 in
357   if size <= 0 then 0
358   else let size = size - (tree_subtree_tags t.doc node Tag.pcdata) in
359        if size < 3 then size else
360          let a = t.attribute_array  in
361          iter_array_tag 0 a (Array.length a) t.doc node size
362 *)
363
364 external tree_closing : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_closing" "noalloc"
365 let closing t n = tree_closing t.doc n
366
367 external tree_num_tags : tree -> int = "caml_xml_tree_num_tags" "noalloc"
368 let num_tags t = tree_num_tags t.doc
369
370 external tree_size : tree -> int = "caml_xml_tree_size" "noalloc"
371 let size t = tree_size t.doc
372
373
374
375
376 module TagS =
377 struct
378   include Ptset.Make (
379     struct type t = int
380            type data = t
381            external hash : t -> int = "%identity"
382            external uid : t -> Uid.t = "%identity"
383            external equal : t -> t -> bool = "%eq"
384            external make : t -> int = "%identity"
385            external node : t -> int = "%identity"
386            external stats : unit -> unit = "%identity"
387            external init : unit -> unit = "%identity"
388     end
389   )
390   let to_ptset s = fold (Ptset.Int.add) s Ptset.Int.empty
391 end
392
393 module TSTSCache =
394   Hashtbl.Make(struct type t = TagS.t * TagS.t
395                       let hash (x, y) =
396                         HASHINT2(Uid.to_int x.TagS.Node.id,
397                                  Uid.to_int y.TagS.Node.id)
398                       let equal u v =
399                         let u1,u2 = u
400                         and v1,v2 = v in
401                         u1 == v1 && u2 == v2
402   end)
403 module TagTSCache =
404   Hashtbl.Make(struct type t = Tag.t * TagS.t
405                       let hash (x, y) =
406                         HASHINT2(x, Uid.to_int y.TagS.Node.id)
407                       let equal u v =
408                         let u1,u2 = u
409                         and v1,v2 = v in
410                         u1 == v1 && u2 == v2
411   end)
412
413 let add_cache = TagTSCache.create 1023
414 let union_cache = TSTSCache.create 1023
415 let subset_cache = TSTSCache.create 1023
416
417 let clear_cache () =
418   TSTSCache.clear union_cache;
419   TSTSCache.clear subset_cache;
420   TagTSCache.clear add_cache
421
422 let _subset x y =
423   (x == y) || (x == TagS.empty) ||
424     if y == TagS.empty then false
425     else
426       let key = (x, y) in
427       try
428         TSTSCache.find subset_cache key
429       with
430       | Not_found ->
431         let z = TagS.subset x y in
432         TSTSCache.add subset_cache key z; z
433
434 let order ((x, y) as z) =
435   if x.TagS.Node.id <= y.TagS.Node.id then z
436   else (y, x)
437
438 let _union x y =
439   if _subset x y then y
440   else if _subset y x then x
441   else
442     let key = order (x, y) in
443     try
444       TSTSCache.find union_cache key
445     with
446     | Not_found ->
447       let z = TagS.union x y in
448       TSTSCache.add union_cache key z; z
449
450 let _add t s =
451   let key = (t,s) in
452   try
453     TagTSCache.find add_cache key
454   with
455   | Not_found ->
456     let z = TagS.add t s in
457     TagTSCache.add add_cache key z;z
458
459 let child_sibling_labels tree =
460   let table_c = Array.create (tree_num_tags tree) TagS.empty in
461   let table_n = Array.copy table_c in
462   let rec loop node =
463     if node == nil then TagS.empty
464     else
465       let children = loop (tree_first_child tree node) in
466       let tag = tree_tag tree node in
467       let () =
468         let tc = table_c.(tag) in
469         if _subset children tc then ()
470         else table_c.(tag) <-  _union tc children
471       in
472       let siblings = loop (tree_next_sibling tree node) in
473       let () =
474         let tn = table_n.(tag) in
475         if _subset siblings tn then ()
476         else table_n.(tag) <- _union tn siblings
477       in
478       _add tag siblings
479   in
480   ignore (loop root);
481   table_c, table_n
482
483 let descendant_labels tree =
484   let table_d = Array.create (tree_num_tags tree) TagS.empty in
485   let rec loop node =
486     if node == nil then  TagS.empty else
487       let d1 = loop (tree_first_child tree node) in
488       let d2 = loop (tree_next_sibling tree node) in
489       let tag = tree_tag tree node in
490       let () =
491         let td = table_d.(tag) in
492         if _subset d1 td then ()
493         else table_d.(tag) <- _union td d1;
494       in
495       _add tag (_union d1 d2)
496   in
497   ignore (loop root);
498   table_d
499
500 let collect_labels tree =
501   let table_f = Array.create (tree_num_tags tree) TagS.empty in
502   let table_n = Array.copy table_f in
503   let table_c = Array.copy table_f in
504   let table_d = Array.copy table_f in
505   let rec loop node foll_siblings descendants followings =
506     if node == nil then foll_siblings, descendants, followings else
507       let tag = tree_tag tree node in
508       let () =
509         let tf = table_f.(tag) in
510         if _subset followings tf then ()
511         else table_f.(tag) <- _union tf followings in
512       let () =
513         let tn = table_n.(tag) in
514         if _subset foll_siblings tn then ()
515         else table_n.(tag) <- _union tn foll_siblings in
516       let children, n_descendants, n_followings =
517         loop (tree_last_child tree node) TagS.empty TagS.empty followings
518       in
519       let () =
520         let tc = table_c.(tag) in
521         if _subset children tc then ()
522         else table_c.(tag) <- _union tc children
523       in
524       let () =
525         let td = table_d.(tag) in
526         if _subset n_descendants td then ()
527         else table_d.(tag) <- _union td n_descendants
528       in
529       loop (tree_prev_sibling tree node)
530         (_add tag foll_siblings)
531         (_add tag (_union n_descendants descendants))
532         (_add tag n_followings)
533   in
534   ignore (loop root TagS.empty TagS.empty TagS.empty);
535   table_f, table_n, table_c, table_d
536
537
538 let is_nil t = t == nil
539 let is_node t = t != nil
540 let is_root t = t == root
541
542 let node_of_t t  =
543   LOG ( __ "indexing" 2 "%s\n" "Initializing tag structure");
544   let _ = Tag.init (mk_tag_ops t) in
545   LOG ( __ "indexing" 2 "%s\n" "Starting tag table construction");
546   let f, n, c, d = time collect_labels t ~msg:"Building tag relationship table" in
547   let c = Array.map TagS.to_ptset c in
548   let n = Array.map TagS.to_ptset n in
549   let f = Array.map TagS.to_ptset f in
550   let d = Array.map TagS.to_ptset d in
551   let () = clear_cache () in
552   let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
553   let elements = Ptset.Int.add Tag.document_node
554     (Ptset.Int.remove Tag.pcdata
555        (Ptset.Int.diff d.(Tag.document_node) attributes))
556   in
557   { doc= t;
558     attributes = attributes;
559     attribute_array = tag_list_of_set attributes;
560     elements = elements;
561     children = c;
562     siblings = n;
563     descendants = d;
564     followings = f
565
566   }
567
568
569 let parse_xml_uri str = node_of_t (TreeBuilder.parse_file str)
570 let parse_xml_string str = node_of_t (TreeBuilder.parse_string str)
571
572 let size t = tree_size t.doc;;
573
574 let magic_string = "SXSI_INDEX"
575 let version_string = "4"
576
577 let pos fd =
578   Unix.lseek fd 0  Unix.SEEK_CUR
579
580 let pr_pos fd = Logger.print err_formatter "At position %i@\n" (pos fd)
581
582 let write fd s =
583   let sl = String.length s in
584   let ssl = Printf.sprintf "%020i" sl in
585   ignore (Unix.write fd ssl 0 20);
586   ignore (Unix.write fd s 0 (String.length s))
587
588 let rec really_read fd buffer start length =
589   if length <= 0 then () else
590     match Unix.read fd buffer start length with
591       0 -> raise End_of_file
592     | r -> really_read fd buffer (start + r) (length - r);;
593
594 let read fd =
595   let buffer = String.create 20 in
596   let _ =  really_read fd buffer 0 20 in
597   let size = int_of_string buffer in
598   let buffer = String.create size in
599   let _ =  really_read fd buffer 0 size in
600   buffer
601
602 let save_tag_table channel t =
603   let t = Array.map (fun s -> Array.of_list (Ptset.Int.elements s)) t in
604   Marshal.to_channel channel t []
605
606 let save t str =
607   let fd = Unix.openfile str [ Unix.O_WRONLY;Unix.O_TRUNC;Unix.O_CREAT] 0o644 in
608   let out_c = Unix.out_channel_of_descr fd in
609   let index_prefix = Filename.chop_suffix str ".srx" in
610   let _ = set_binary_mode_out out_c true in
611   output_string out_c magic_string;
612   output_char out_c '\n';
613   output_string out_c version_string;
614   output_char out_c '\n';
615   save_tag_table out_c t.children;
616   save_tag_table out_c t.siblings;
617   save_tag_table out_c t.descendants;
618   save_tag_table out_c t.followings;
619     (* we need to move the fd to the correct position *)
620   flush out_c;
621   ignore (Unix.lseek fd (pos_out out_c) Unix.SEEK_SET);
622   tree_save t.doc fd index_prefix;
623   close_out out_c
624 ;;
625 let load_tag_table channel =
626   let table : int array array = Marshal.from_channel channel in
627   Array.map (fun a -> Ptset.Int.from_list (Array.to_list a)) table
628
629 let load ?(sample=64) ?(load_text=true) str =
630   let fd = Unix.openfile str [ Unix.O_RDONLY ] 0o644 in
631   let in_c = Unix.in_channel_of_descr fd in
632   let index_prefix = Filename.chop_suffix str ".srx" in
633   let _ = set_binary_mode_in in_c true in
634   let load_table () =
635     (let ms = input_line in_c in if ms <> magic_string then failwith "Invalid index file");
636     (let vs = input_line in_c in if vs <> version_string then failwith "Unsupported index format");
637     let c = load_tag_table in_c in
638     let s = load_tag_table in_c in
639     let d = load_tag_table in_c in
640     let f = load_tag_table in_c in
641     c,s,d,f
642   in
643   let c, s, d, f = time ~msg:"Loading tag table"(load_table) () in
644   ignore(Unix.lseek fd (pos_in in_c) Unix.SEEK_SET);
645   let xml_tree = tree_load fd index_prefix load_text sample in
646   let () = Tag.init (Obj.magic xml_tree) in
647   let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
648   let elements = Ptset.Int.add Tag.document_node
649     (Ptset.Int.remove Tag.pcdata
650        (Ptset.Int.diff d.(Tag.document_node) attributes))
651   in
652   let tree = { doc = xml_tree;
653                attributes = attributes;
654                attribute_array = tag_list_of_set attributes;
655                elements = elements;
656                children = c;
657                siblings = s;
658                descendants = d;
659                followings = f
660              }
661   in close_in in_c;
662   tree
663
664
665
666
667 let equal a b = a == b
668
669 let nts = function
670 -1 -> "Nil"
671   | i -> Printf.sprintf "Node (%i)"  i
672
673 let dump_node t = nts (Node.to_int t)
674
675
676
677 type query_result = { bv : bit_vector;
678                       pos : node array;
679                     }
680
681 external tree_flush : tree -> Unix.file_descr -> unit = "caml_xml_tree_flush"
682 let flush t fd = tree_flush t.doc fd
683
684 external text_prefix : tree -> string -> bool -> query_result = "caml_text_collection_prefix_bv"
685 let text_prefix t s b = text_prefix t.doc s b
686
687 external text_suffix : tree -> string -> bool -> query_result = "caml_text_collection_suffix_bv"
688 let text_suffix t s b = text_suffix t.doc s b
689
690 external text_equals : tree -> string -> bool -> query_result = "caml_text_collection_equals_bv"
691 let text_equals t s b = text_equals t.doc s b
692
693 external text_contains : tree -> string -> bool -> query_result = "caml_text_collection_contains_bv"
694 let text_contains t s b = text_contains t.doc s b
695
696
697 module Predicate = Hcons.Make (
698   struct
699     type _t = t
700     type t = (_t -> node -> bool) ref
701     let hash t = Hashtbl.hash t
702     let equal t1 t2 = t1 == t2
703   end)
704
705 let string_of_query query =
706   match query with
707   | `Prefix -> "starts-with"
708   | `Suffix -> "ends-with"
709   | `Equals -> "equals"
710   | `Contains -> "contains"
711 ;;
712
713 let query_fun = function
714   | `Prefix -> text_prefix
715   | `Suffix -> text_suffix
716   | `Equals -> text_equals
717   | `Contains -> text_contains
718 ;;
719
720 let _pred_cache = Hashtbl.create 17
721 ;;
722 let mk_pred query s =
723   LOG ( __ "bottom-up" 3 "Calling mk_pred for '%s'\n" s);
724   let f = query_fun query  in
725   let memo = ref (fun _ _ -> failwith "Undefined") in
726   memo := begin fun tree node ->
727     let results =
728       try Hashtbl.find _pred_cache (query,s) with
729         Not_found ->
730           time ~count:1 ~msg:(Printf.sprintf "Computing text query %s(%s)"
731                                 (string_of_query query) s)
732             (f tree) s true
733     in
734     let bv = results.bv in
735     memo := begin fun _ n ->
736       let r = bit_vector_unsafe_get bv (Node.to_int n) in
737       LOG( __  "bottom-up" 3 "Running predicate on node %i = %b@\n" (Node.to_int n) r);
738       r
739     end;
740     let r = bit_vector_unsafe_get bv (Node.to_int node) in
741     LOG( __  "bottom-up" 3 "Running predicate on node %i = %b@\n" (Node.to_int node) r);
742     r
743   end;
744   Predicate.make memo
745
746
747 let full_text_prefix t s = (text_prefix t s true).pos
748
749 let full_text_suffix t s = (text_suffix t s true).pos
750
751 let full_text_equals t s = (text_equals t s true).pos
752
753 let full_text_contains t s = (text_contains t s true).pos
754
755 let full_text_query q t s =
756   let res = (query_fun q) t s true in
757   Hashtbl.replace _pred_cache (q,s) res;
758   res.pos
759
760 let stats tree =
761       let h = Hashtbl.create 1024 in
762       let depth = ref 0 in
763       let numleaves = ref 0 in
764       let numtexts = ref 0 in
765     let rec traverse tree t p d =
766       if is_nil t then
767         let oldc =
768           try
769             Hashtbl.find h p
770           with Not_found -> 0
771         in
772         Hashtbl.replace h p (oldc + 1);
773         if d > !depth then depth := d;
774         incr numleaves
775       else
776         let label = tree_tag tree t in
777         if label == Tag.pcdata || label == Tag.attribute_data then incr numtexts;
778         iter_siblings tree t (label::p) (d+1)
779     and iter_siblings tree t p d =
780       if is_nil t then () else
781         let fs = tree_first_child tree t in
782         traverse tree fs p d;
783         let ns = tree_next_sibling tree t in
784         iter_siblings tree ns p d
785     in
786     traverse tree.doc root [] 0;
787     let sumdepth = Hashtbl.fold (fun p c acc -> (List.length p) * c + acc) h 0 in
788     let alltags = Ptset.Int.union tree.elements tree.attributes in
789     Logger.print err_formatter "Statistics :@\n\
790 Average depth: %f@\n\
791 Longest path: %i@\n\
792 Number of distinct paths: %i@\n\
793 Number of nodes: %i@\n\
794 Number of leaves: %i@\n\
795 Number of pcdata/cdata nodes: %i@\n\
796 Number of distinct tags: %i@\n\
797 Largest tag id: %i@\n@?"
798       (float_of_int sumdepth /. float_of_int !numleaves)
799       !depth
800       (Hashtbl.length h)
801       (tree_subtree_size tree.doc root)
802       !numleaves
803       !numtexts
804       (Ptset.Int.cardinal alltags)
805       (Ptset.Int.max_elt alltags)
806
807
808 type tree_pointer = tree
809 let get_tree_pointer x = x.doc