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 (******************************************************************************)
11 external init_lib : unit -> unit = "sxsi_cpp_init"
13 exception CPlusPlusError of string
15 let () = Callback.register_exception "CPlusPlusError" (CPlusPlusError "")
19 type node = [ `Tree ] Node.t
24 external register_tag : tree -> string -> Tag.t = "caml_xml_tree_register_tag"
26 external tag_name : tree -> Tag.t -> string = "caml_xml_tree_get_tag_name"
28 let tag t = (); fun s ->
31 | "<@>" -> Tag.attribute
32 | "" -> Tag.document_node
33 | "<@$>" -> Tag.attribute_data
34 | _ -> register_tag t s
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!>"
48 Tag.to_string = to_string t;
49 Tag.translate = translate
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"
64 if Buffer.length t > 0 then begin
66 text b (Buffer.contents t);
71 let output_attr b name value =
72 let atname = "<@>" ^ name in
79 let start_element_handler b t tag attr_list =
86 List.iter (fun (name, value) -> output_attr b name value) l;
90 let end_element_handler b t tag =
94 let character_data_handler _b t text =
95 Buffer.add_string t text
97 let create_parser () =
98 let buf = Buffer.create 512 in
99 let build = create () in
100 let parser_ = Expat.parser_create ~encoding:None in
106 Expat.set_start_element_handler parser_ (start_element_handler build buf);
107 Expat.set_end_element_handler parser_ (end_element_handler build buf);
108 Expat.set_character_data_handler parser_ (character_data_handler build buf);
109 open_document build !Options.index_empty_texts !Options.sample_factor
110 !Options.disable_text_collection !Options.text_index_type;
115 let parser_, finalizer = create_parser () in
116 Expat.parse parser_ s;
119 let parse_file file =
120 let in_chan = open_in file in
121 let buffer = String.create 4096 in
122 let parser_, finalizer = create_parser () in
126 let read = input in_chan buffer 0 4096 in
127 if read == 0 then raise End_of_file else
128 Expat.parse_sub parser_ buffer 0 read;
132 | End_of_file -> close_in in_chan
144 type bit_vector = string
146 external bool_of_int : int -> bool = "%identity"
148 let bit_vector_unsafe_get v i =
150 (((Char.code (String.unsafe_get v (i lsr 3))) lsr (i land 7)) land 1)
154 elements: Ptset.Int.t;
155 attributes: Ptset.Int.t;
156 attribute_array : Tag.t array;
157 children : Ptset.Int.t array;
158 siblings : Ptset.Int.t array;
159 descendants: Ptset.Int.t array;
160 followings: Ptset.Int.t array;
164 let tag_operations t = mk_tag_ops t.doc
166 external parse_xml_uri : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_uri"
167 external parse_xml_string : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_string"
169 external tree_print_xml_fast3 : tree -> [`Tree ] Node.t -> Unix.file_descr -> unit = "caml_xml_tree_print"
170 let print_xml t n fd =
171 tree_print_xml_fast3 t.doc n fd
174 external tree_save : tree -> Unix.file_descr -> string -> unit = "caml_xml_tree_save"
175 external tree_load : Unix.file_descr -> string -> bool -> int -> tree = "caml_xml_tree_load"
177 external nullt : unit -> 'a Node.t = "caml_xml_tree_nullt"
179 let nil : [`Tree ] Node.t = Node.nil
180 let root : [`Tree ] Node.t = Node.null
184 external unordered_set_alloc : int -> unordered_set = "caml_unordered_set_alloc"
185 external unordered_set_length : unordered_set -> int = "caml_unordered_set_length"
186 external unordered_set_insert : unordered_set -> int -> unit = "caml_unordered_set_set" "noalloc"
188 module HPtset = Hashtbl.Make(Ptset.Int)
190 let vector_htbl = HPtset.create MED_H_SIZE
192 let unordered_set_of_set s =
194 HPtset.find vector_htbl s
197 let v = unordered_set_alloc (Ptset.Int.cardinal s) in
198 let _ = Ptset.Int.iter (fun e -> unordered_set_insert v e) s in
199 HPtset.add vector_htbl s v; v
201 let ptset_to_vector = unordered_set_of_set
203 (** tree interface *)
205 external tree_root : tree -> [`Tree] Node.t = "caml_xml_tree_root" "noalloc"
208 external tree_first_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_child" "noalloc"
209 let first_child t n = tree_first_child t.doc n
211 external tree_first_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_element" "noalloc"
212 let first_element t n = tree_first_element t.doc n
214 external tree_tagged_child : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_child" "noalloc"
215 let tagged_child t n tag = tree_tagged_child t.doc n tag
217 external tree_select_child : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_child" "noalloc"
218 let select_child t n tag_set = tree_select_child t.doc n tag_set
220 external tree_last_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_last_child" "noalloc"
221 let last_child t n = tree_last_child t.doc n
225 external tree_next_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_sibling" "noalloc"
226 let next_sibling t n = tree_next_sibling t.doc n
228 external tree_next_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_element" "noalloc"
229 let next_element t n = tree_next_element t.doc n
231 external tree_next_node_before : tree -> [`Tree] Node.t -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_node_before" "noalloc"
232 let next_node_before t n ctx = tree_next_node_before t.doc n ctx
234 external tree_tagged_following_sibling : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_following_sibling" "noalloc"
235 let tagged_following_sibling t n tag = tree_tagged_following_sibling t.doc n tag
237 external tree_select_following_sibling : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_following_sibling" "noalloc"
238 let select_following_sibling t n tag_set = tree_select_following_sibling t.doc n tag_set
240 external tree_prev_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_prev_sibling" "noalloc"
241 let prev_sibling t n = tree_prev_sibling t.doc n
245 external tree_tagged_descendant : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_descendant" "noalloc"
246 let tagged_descendant t n tag = tree_tagged_descendant t.doc n tag
248 external tree_tagged_next : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_next" "noalloc"
249 let tagged_next t n tag = tree_tagged_next t.doc n tag
251 external tree_select_descendant : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_descendant" "noalloc"
252 let select_descendant t n tag_set = tree_select_descendant t.doc n tag_set
254 external tree_tagged_following_before : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_following_before" "noalloc"
255 let tagged_following_before t n tag ctx = tree_tagged_following_before t.doc n tag ctx
257 external tree_select_following_before : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_select_following_before" "noalloc"
258 let select_following_before t n tag_set ctx = tree_select_following_before t.doc n tag_set ctx
260 external tree_parent : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_parent" "noalloc"
261 let parent t n = tree_parent t.doc n
263 external tree_binary_parent : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_binary_parent"
265 let binary_parent t n = tree_binary_parent t.doc n
268 external tree_tag : tree -> [`Tree] Node.t -> Tag.t = "caml_xml_tree_tag" "noalloc"
269 let tag t n = tree_tag t.doc n
271 external tree_is_first_child : tree -> [ `Tree ] Node.t -> bool = "caml_xml_tree_is_first_child" "noalloc"
272 let is_first_child t n = tree_is_first_child t.doc n
274 external tree_is_right_descendant : tree -> [ `Tree ] Node.t -> [`Tree] Node.t -> bool =
275 "caml_xml_tree_is_right_descendant" "noalloc"
277 let is_right_descendant t n1 n2 = tree_is_right_descendant t.doc n1 n2
280 let node_tags t = Ptset.Int.add Tag.document_node t.descendants.(Tag.document_node)
282 let attribute_tags t = t.attributes
284 let element_tags t = t.elements
287 t.children.(tag), t.descendants.(tag), t.siblings.(tag), t.followings.(tag)
290 let dump_tag_table t =
291 eprintf "Child tags:\n%!";
293 (fun tag set -> eprintf "%s: %a\n%!"
294 (Tag.to_string tag) TagSet.print (TagSet.inj_positive set))
296 eprintf "-----------------------------\n%!";
297 eprintf "Descendant tags:\n%!";
299 (fun tag set -> eprintf "%s: %a\n%!"
300 (Tag.to_string tag) TagSet.print (TagSet.inj_positive set))
302 eprintf "-----------------------------\n%!";
303 eprintf "Sibling tags:\n%!";
305 (fun tag set -> eprintf "%s: %a\n%!"
306 (Tag.to_string tag) TagSet.print (TagSet.inj_positive set))
308 eprintf "-----------------------------\n%!";
309 eprintf "Following tags:\n%!";
311 (fun tag set -> eprintf "%s: %a\n%!"
312 (Tag.to_string tag) TagSet.print (TagSet.inj_positive set))
314 eprintf "-----------------------------\n%!"
317 external tree_subtree_tags : tree -> [`Tree] Node.t -> Tag.t -> int = "caml_xml_tree_subtree_tags" "noalloc"
318 let subtree_tags t n tag = tree_subtree_tags t.doc n tag
320 external tree_subtree_size : tree -> [`Tree] Node.t -> int = "caml_xml_tree_subtree_size" "noalloc"
321 let subtree_size t n = tree_subtree_size t.doc n
323 let subtree_elements t node =
324 let size = tree_subtree_size t.doc node - 1 in
326 else let size = size - (tree_subtree_tags t.doc node Tag.pcdata) in
327 if size < 2 then size else
328 let acc = ref size in
329 for i = 0 to Array.length t.attribute_array - 1 do
330 acc := !acc - tree_subtree_tags t.doc node t.attribute_array.(i)
334 external tree_closing : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_closing" "noalloc"
335 let closing t n = tree_closing t.doc n
337 external tree_num_tags : tree -> int = "caml_xml_tree_num_tags" "noalloc"
338 let num_tags t = tree_num_tags t.doc
340 external tree_size : tree -> int = "caml_xml_tree_size" "noalloc"
341 let size t = tree_size t.doc
346 let rec loop left node acc_d total_d num_leaves =
348 (acc_d+total_d,if left then num_leaves+1 else num_leaves)
350 let d,td = loop true (tree_first_child tree node) (acc_d+1) total_d num_leaves in
351 loop false (tree_next_sibling tree node) (acc_d) d td
353 let a,b = loop true root 0 0 0
355 Printf.eprintf "Average depth: %f, number of leaves %i\n%!" ((float_of_int a)/. (float_of_int b)) b
363 external hash : t -> int = "%identity"
364 external uid : t -> Uid.t = "%identity"
365 external equal : t -> t -> bool = "%eq"
366 external make : t -> int = "%identity"
367 external node : t -> int = "%identity"
368 external stats : unit -> unit = "%identity"
371 let to_ptset s = fold (Ptset.Int.add) s Ptset.Int.empty
375 Hashtbl.Make(struct type t = TagS.t * TagS.t
377 HASHINT2(Uid.to_int x.TagS.Node.id,
378 Uid.to_int y.TagS.Node.id)
385 Hashtbl.Make(struct type t = Tag.t * TagS.t
387 HASHINT2(x, Uid.to_int y.TagS.Node.id)
394 let add_cache = TagTSCache.create 1023
395 let union_cache = TSTSCache.create 1023
396 let subset_cache = TSTSCache.create 1023
399 TSTSCache.clear union_cache;
400 TSTSCache.clear subset_cache;
401 TagTSCache.clear add_cache
404 (x == y) || (x == TagS.empty) ||
405 if y == TagS.empty then false
409 TSTSCache.find subset_cache key
412 let z = TagS.subset x y in
413 TSTSCache.add subset_cache key z; z
415 let order ((x, y) as z) =
416 if x.TagS.Node.id <= y.TagS.Node.id then z
420 if _subset x y then y
421 else if _subset y x then x
423 let key = order (x, y) in
425 TSTSCache.find union_cache key
428 let z = TagS.union x y in
429 TSTSCache.add union_cache key z; z
434 TagTSCache.find add_cache key
437 let z = TagS.add t s in
438 TagTSCache.add add_cache key z;z
440 let child_sibling_labels tree =
441 let table_c = Array.create (tree_num_tags tree) TagS.empty in
442 let table_n = Array.copy table_c in
444 if node == nil then TagS.empty
446 let children = loop (tree_first_child tree node) in
447 let tag = tree_tag tree node in
449 let tc = table_c.(tag) in
450 if _subset children tc then ()
451 else table_c.(tag) <- _union tc children
453 let siblings = loop (tree_next_sibling tree node) in
455 let tn = table_n.(tag) in
456 if _subset siblings tn then ()
457 else table_n.(tag) <- _union tn siblings
464 let descendant_labels tree =
465 let table_d = Array.create (tree_num_tags tree) TagS.empty in
467 if node == nil then TagS.empty else
468 let d1 = loop (tree_first_child tree node) in
469 let d2 = loop (tree_next_sibling tree node) in
470 let tag = tree_tag tree node in
472 let td = table_d.(tag) in
473 if _subset d1 td then ()
474 else table_d.(tag) <- _union td d1;
476 _add tag (_union d1 d2)
481 let collect_labels tree =
482 let table_f = Array.create (tree_num_tags tree) TagS.empty in
483 let table_n = Array.copy table_f in
484 let table_c = Array.copy table_f in
485 let table_d = Array.copy table_f in
486 let rec loop node foll_siblings descendants followings =
487 if node == nil then foll_siblings, descendants, followings else
488 let tag = tree_tag tree node in
490 let tf = table_f.(tag) in
491 if _subset followings tf then ()
492 else table_f.(tag) <- _union tf followings in
494 let tn = table_n.(tag) in
495 if _subset foll_siblings tn then ()
496 else table_n.(tag) <- _union tn foll_siblings in
497 let children, n_descendants, n_followings =
498 loop (tree_last_child tree node) TagS.empty TagS.empty followings
501 let tc = table_c.(tag) in
502 if _subset children tc then ()
503 else table_c.(tag) <- _union tc children
506 let td = table_d.(tag) in
507 if _subset n_descendants td then ()
508 else table_d.(tag) <- _union td n_descendants
510 loop (tree_prev_sibling tree node)
511 (_add tag foll_siblings)
512 (_add tag (_union n_descendants descendants))
513 (_add tag n_followings)
515 ignore (loop root TagS.empty TagS.empty TagS.empty);
516 table_f, table_n, table_c, table_d
519 let is_nil t = t == nil
520 let is_node t = t != nil
521 let is_root t = t == root
524 let _ = Tag.init (mk_tag_ops t) in
525 let f, n, c, d = time collect_labels t ~msg:"Building tag relationship table" in
526 let c = Array.map TagS.to_ptset c in
527 let n = Array.map TagS.to_ptset n in
528 let f = Array.map TagS.to_ptset f in
529 let d = Array.map TagS.to_ptset d in
530 let () = clear_cache () in
531 let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
532 let elements = Ptset.Int.add Tag.document_node
533 (Ptset.Int.remove Tag.pcdata
534 (Ptset.Int.diff d.(Tag.document_node) attributes))
537 attributes = attributes;
538 attribute_array = Array.of_list (Ptset.Int.elements attributes);
548 let parse_xml_uri str = node_of_t (TreeBuilder.parse_file str)
549 let parse_xml_string str = node_of_t (TreeBuilder.parse_string str)
551 let size t = tree_size t.doc;;
553 let magic_string = "SXSI_INDEX"
554 let version_string = "3"
557 Unix.lseek fd 0 Unix.SEEK_CUR
559 let pr_pos fd = Printf.eprintf "At position %i\n%!" (pos fd)
562 let sl = String.length s in
563 let ssl = Printf.sprintf "%020i" sl in
564 ignore (Unix.write fd ssl 0 20);
565 ignore (Unix.write fd s 0 (String.length s))
567 let rec really_read fd buffer start length =
568 if length <= 0 then () else
569 match Unix.read fd buffer start length with
570 0 -> raise End_of_file
571 | r -> really_read fd buffer (start + r) (length - r);;
574 let buffer = String.create 20 in
575 let _ = really_read fd buffer 0 20 in
576 let size = int_of_string buffer in
577 let buffer = String.create size in
578 let _ = really_read fd buffer 0 size in
581 let save_tag_table channel t =
582 let t = Array.map (fun s -> Array.of_list (Ptset.Int.elements s)) t in
583 Marshal.to_channel channel t []
586 let fd = Unix.openfile str [ Unix.O_WRONLY;Unix.O_TRUNC;Unix.O_CREAT] 0o644 in
587 let out_c = Unix.out_channel_of_descr fd in
588 let _ = set_binary_mode_out out_c true in
589 output_string out_c magic_string;
590 output_char out_c '\n';
591 output_string out_c version_string;
592 output_char out_c '\n';
593 save_tag_table out_c t.children;
594 save_tag_table out_c t.siblings;
595 save_tag_table out_c t.descendants;
596 save_tag_table out_c t.followings;
597 (* we need to move the fd to the correct position *)
599 ignore (Unix.lseek fd (pos_out out_c) Unix.SEEK_SET);
600 tree_save t.doc fd str;
603 let load_tag_table channel =
604 let table : int array array = Marshal.from_channel channel in
605 Array.map (fun a -> Ptset.Int.from_list (Array.to_list a)) table
607 let load ?(sample=64) ?(load_text=true) str =
608 let fd = Unix.openfile str [ Unix.O_RDONLY ] 0o644 in
609 let in_c = Unix.in_channel_of_descr fd in
610 let _ = set_binary_mode_in in_c true in
612 (let ms = input_line in_c in if ms <> magic_string then failwith "Invalid index file");
613 (let vs = input_line in_c in if vs <> version_string then failwith "Invalid version file");
614 let c = load_tag_table in_c in
615 let s = load_tag_table in_c in
616 let d = load_tag_table in_c in
617 let f = load_tag_table in_c in
620 let c, s, d, f = time ~msg:"Loading tag table"(load_table) () in
621 ignore(Unix.lseek fd (pos_in in_c) Unix.SEEK_SET);
622 let xml_tree = tree_load fd str load_text sample in
623 let () = Tag.init (Obj.magic xml_tree) in
624 let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
625 let elements = Ptset.Int.add Tag.document_node
626 (Ptset.Int.remove Tag.pcdata
627 (Ptset.Int.diff d.(Tag.document_node) attributes))
629 let tree = { doc = xml_tree;
630 attributes = attributes;
631 attribute_array = Array.of_list (Ptset.Int.elements attributes);
644 let equal a b = a == b
648 | i -> Printf.sprintf "Node (%i)" i
650 let dump_node t = nts (Node.to_int t)
654 type query_result = { bv : bit_vector;
658 external tree_flush : tree -> Unix.file_descr -> unit = "caml_xml_tree_flush"
659 let flush t fd = tree_flush t.doc fd
661 external text_prefix : tree -> string -> query_result = "caml_text_collection_prefix_bv"
662 let text_prefix t s = text_prefix t.doc s
664 external text_suffix : tree -> string -> query_result = "caml_text_collection_suffix_bv"
665 let text_suffix t s = text_suffix t.doc s
667 external text_equals : tree -> string -> query_result = "caml_text_collection_equals_bv"
668 let text_equals t s = text_equals t.doc s
670 external text_contains : tree -> string -> query_result = "caml_text_collection_contains_bv"
671 let text_contains t s = text_contains t.doc s
674 module Predicate = Hcons.Make (
677 type t = (_t -> node -> bool) ref
678 let hash t = Hashtbl.hash t
679 let equal t1 t2 = t1 == t2
682 let string_of_query query =
684 | `Prefix -> "starts-with"
685 | `Suffix -> "ends-with"
686 | `Equals -> "equals"
687 | `Contains -> "contains"
690 let query_fun = function
691 | `Prefix -> text_prefix
692 | `Suffix -> text_suffix
693 | `Equals -> text_equals
694 | `Contains -> text_contains
697 let _pred_cache = Hashtbl.create 17
699 let mk_pred query s =
700 let f = query_fun query in
701 let memo = ref (fun _ _ -> failwith "Undefined") in
702 memo := begin fun tree node ->
704 try Hashtbl.find _pred_cache (query,s) with
706 time ~count:1 ~msg:(Printf.sprintf "Computing text query %s(%s)"
707 (string_of_query query) s)
710 let bv = results.bv in
711 memo := begin fun _ n ->
713 bit_vector_unsafe_get bv (Node.to_int n)
715 D_TRACE_(Printf.eprintf "Result of memoized call to query %s is %b for node %i\n" s b (Node.to_int n));
718 let b = bit_vector_unsafe_get bv (Node.to_int node) in
719 D_TRACE_(Printf.eprintf "Result is %b for node %i\n" b (Node.to_int node));
725 let full_text_prefix t s = (text_prefix t s).pos
727 let full_text_suffix t s = (text_suffix t s).pos
729 let full_text_equals t s = (text_equals t s).pos
731 let full_text_contains t s = (text_contains t s).pos
733 let full_text_query q t s =
734 let res = (query_fun q) t s in
735 Hashtbl.replace _pred_cache (q,s) res;