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