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