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 (******************************************************************************)
10 external init_lib : unit -> unit = "sxsi_cpp_init"
12 exception CPlusPlusError of string
14 let () = Callback.register_exception "CPlusPlusError" (CPlusPlusError "")
18 type node = [ `Tree ] Node.t
22 external register_tag : tree -> string -> Tag.t = "caml_xml_tree_register_tag"
24 external tag_name : tree -> Tag.t -> string = "caml_xml_tree_get_tag_name"
26 let tag t = (); fun s ->
29 | "<@>" -> Tag.attribute
30 | "" -> Tag.document_node
31 | "<@$>" -> Tag.attribute_data
32 | _ -> register_tag t s
36 if t == Tag.pcdata then "<$>"
37 else if t == Tag.attribute_data then "<@$>"
38 else if t == Tag.attribute then "<@>"
39 else if t == Tag.nullt then "<!NIL!>"
46 Tag.to_string = to_string t;
47 Tag.translate = translate
53 external create : unit -> t = "caml_xml_tree_builder_create"
54 external open_document : t -> int -> bool -> int -> unit = "caml_xml_tree_builder_open_document"
55 external close_document : t -> tree = "caml_xml_tree_builder_close_document"
56 external open_tag : t -> string -> unit = "caml_xml_tree_builder_open_tag"
57 external close_tag : t -> string -> unit = "caml_xml_tree_builder_close_tag"
58 external text : t -> string -> unit = "caml_xml_tree_builder_text"
64 (c == '\n' || c == '\t' || c == ' ') && loop len (i+1)
68 loop (String.length s) 0
72 let event_counter = ref 0 in
75 if !event_counter land 0xffffff == 0 then
76 Logger.print Format.err_formatter "Current position: %i@\n@?" (Expat.get_current_byte_index parser_))
80 if Buffer.length t > 0 then begin
81 let s = Buffer.contents t in
90 let output_attr b name value =
91 let atname = "<@>" ^ name in
98 let start_element_handler parser_ b t tag attr_list =
105 List.iter (fun (name, value) -> output_attr b name value) l;
109 let end_element_handler parser_ b t tag =
113 let character_data_handler parser_ _ t text =
114 Buffer.add_string t text
116 let create_parser () =
117 let buf = Buffer.create 512 in
118 let build = create () in
119 let parser_ = Expat.parser_create ~encoding:None in
123 Logger.print Format.err_formatter "Finished parsing@\n";
124 Logger.print Format.err_formatter "Starting index construction@\n";
125 let r = close_document build in
126 Logger.print Format.err_formatter "Finished index construction@\n";
129 Expat.set_start_element_handler parser_ (start_element_handler parser_ build buf);
130 Expat.set_end_element_handler parser_ (end_element_handler parser_ build buf);
131 Expat.set_character_data_handler parser_ (character_data_handler parser_ build buf);
132 Logger.print Format.err_formatter "Started parsing@\n";
133 open_document build !Options.sample_factor !Options.disable_text_collection !Options.text_index_type;
138 let parser_, finalizer = create_parser () in
139 Expat.parse parser_ s;
142 let parse_file file =
143 let in_chan = open_in file in
144 let buffer = String.create 4096 in
145 let parser_, finalizer = create_parser () in
149 let read = input in_chan buffer 0 4096 in
150 if read == 0 then raise End_of_file else
151 Expat.parse_sub parser_ buffer 0 read;
155 | End_of_file -> close_in in_chan
165 type bit_vector = string
167 external bool_of_int : int -> bool = "%identity"
168 external int_of_bool : bool -> int = "%identity"
170 let bit_vector_unsafe_get v i =
172 (((Char.code (String.unsafe_get v (i lsr 3))) lsr (i land 7)) land 1)
173 let chr (c:int) : char = Obj.magic (c land 0xff)
174 let bit_vector_unsafe_set v i b =
176 let c = Char.code v.[j] in
177 let bit = int_of_bool b in
178 let mask = bit lsl (i land 7) in
179 if b then v.[j] <- chr (c lor mask) else v.[j] <- (chr (c land (lnot mask)))
181 let bit_vector_create n =
182 let len = if n <= 0 then 0 else (n - 1) / 8 + 1 in
183 String.make len '\000'
187 elements: Ptset.Int.t;
188 attributes: Ptset.Int.t;
189 attribute_array : Tag.t array;
190 children : Ptset.Int.t array;
191 siblings : Ptset.Int.t array;
192 descendants: Ptset.Int.t array;
193 followings: Ptset.Int.t array;
197 let tag_operations t = mk_tag_ops t.doc
199 external parse_xml_uri : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_uri"
200 external parse_xml_string : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_string"
202 external tree_print_xml_fast3 : tree -> [`Tree ] Node.t -> Unix.file_descr -> unit = "caml_xml_tree_print"
203 let print_xml t n fd =
204 tree_print_xml_fast3 t.doc n fd
207 external tree_save : tree -> Unix.file_descr -> string -> unit = "caml_xml_tree_save"
208 external tree_load : Unix.file_descr -> string -> bool -> int -> tree = "caml_xml_tree_load"
210 external nullt : unit -> 'a Node.t = "caml_xml_tree_nullt"
212 let nil : [`Tree ] Node.t = Node.nil
213 let root : [`Tree ] Node.t = Node.null
217 external unordered_set_alloc : int -> unordered_set = "caml_unordered_set_alloc"
218 external unordered_set_length : unordered_set -> int = "caml_unordered_set_length"
219 external unordered_set_insert : unordered_set -> int -> unit = "caml_unordered_set_set" "noalloc"
221 module HPtset = Hashtbl.Make(Ptset.Int)
223 let vector_htbl = HPtset.create MED_H_SIZE
225 let unordered_set_of_set s =
227 HPtset.find vector_htbl s
230 let v = unordered_set_alloc (Ptset.Int.cardinal s) in
231 let _ = Ptset.Int.iter (fun e -> unordered_set_insert v e) s in
232 HPtset.add vector_htbl s v; v
234 let ptset_to_vector = unordered_set_of_set
236 (** tree interface *)
238 external tree_root : tree -> [`Tree] Node.t = "caml_xml_tree_root" "noalloc"
241 external tree_first_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_child" "noalloc"
242 let first_child t n = tree_first_child t.doc n
244 external tree_first_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_element" "noalloc"
245 let first_element t n = tree_first_element t.doc n
247 external tree_tagged_child : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_child" "noalloc"
248 let tagged_child t n tag = tree_tagged_child t.doc n tag
250 external tree_select_child : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_child" "noalloc"
251 let select_child t n tag_set = tree_select_child t.doc n tag_set
253 external tree_last_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_last_child" "noalloc"
254 let last_child t n = tree_last_child t.doc n
257 external tree_next_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_sibling" "noalloc"
258 let next_sibling t n = tree_next_sibling t.doc n
260 external tree_next_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_element" "noalloc"
261 let next_element t n = tree_next_element t.doc n
264 external tree_tagged_sibling : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_sibling" "noalloc"
265 let tagged_sibling t n tag = tree_tagged_sibling t.doc n tag
268 external tree_select_sibling : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_sibling" "noalloc"
269 let select_sibling t n tag_set = tree_select_sibling t.doc n tag_set
271 external tree_prev_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_prev_sibling" "noalloc"
272 let prev_sibling t n = tree_prev_sibling t.doc n
276 external tree_tagged_descendant : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_descendant" "noalloc"
277 let tagged_descendant t n tag = tree_tagged_descendant t.doc n tag
279 external tree_tagged_next : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_next" "noalloc"
280 let tagged_next t n tag = tree_tagged_next t.doc n tag
282 external tree_select_descendant : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_descendant" "noalloc"
283 let select_descendant t n tag_set = tree_select_descendant t.doc n tag_set
285 external tree_tagged_following_before : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_following_before" "noalloc"
286 let tagged_following_before t n tag ctx = tree_tagged_following_before t.doc n tag ctx
288 external tree_select_following_before : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_select_following_before" "noalloc"
289 let select_following_before t n tag_set ctx = tree_select_following_before t.doc n tag_set ctx
291 external tree_parent : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_parent" "noalloc"
292 let parent t n = tree_parent t.doc n
294 external tree_tag : tree -> [`Tree] Node.t -> Tag.t = "caml_xml_tree_tag" "noalloc"
295 let tag t n = tree_tag t.doc n
297 external tree_is_first_child : tree -> [ `Tree ] Node.t -> bool = "caml_xml_tree_is_first_child" "noalloc"
298 let is_first_child t n = tree_is_first_child t.doc n
300 external tree_is_right_descendant : tree -> [ `Tree ] Node.t -> [`Tree] Node.t -> bool =
301 "caml_xml_tree_is_right_descendant" "noalloc"
303 let is_right_descendant t n1 n2 = tree_is_right_descendant t.doc n1 n2
306 let node_tags t = Ptset.Int.add Tag.document_node t.descendants.(Tag.document_node)
308 let attribute_tags t = t.attributes
310 let element_tags t = t.elements
313 t.children.(tag), t.descendants.(tag), t.siblings.(tag), t.followings.(tag)
316 let dump_tag_table t =
318 let printer ppf set =
319 Logger.print ppf "%s: %a"
320 (Tag.to_string !tag) TagSet.print (TagSet.inj_positive set);
323 let set_printer msg set =
325 Logger.print err_formatter "%s :@\n" msg;
326 Pretty.pp_print_array ~sep:pp_force_newline printer err_formatter set;
327 Logger.print err_formatter "-----------------------------@\n";
329 set_printer "Child tags" t.children;
330 set_printer "Descendant tags" t.descendants;
331 set_printer "Sibling tags" t.siblings;
332 set_printer "Following tags" t.followings
334 external tree_subtree_tags : tree -> [`Tree] Node.t -> Tag.t -> int = "caml_xml_tree_subtree_tags" "noalloc"
335 let subtree_tags t n tag = tree_subtree_tags t.doc n tag
337 external tree_subtree_size : tree -> [`Tree] Node.t -> int = "caml_xml_tree_subtree_size" "noalloc"
338 let subtree_size t n = tree_subtree_size t.doc n
340 let subtree_elements t node =
341 let size = tree_subtree_size t.doc node - 1 in
343 else let size = size - (tree_subtree_tags t.doc node Tag.pcdata) in
344 if size < 2 then size else
345 let acc = ref size in
346 for i = 0 to Array.length t.attribute_array - 1 do
347 acc := !acc - tree_subtree_tags t.doc node t.attribute_array.(i)
351 external tree_closing : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_closing" "noalloc"
352 let closing t n = tree_closing t.doc n
354 external tree_num_tags : tree -> int = "caml_xml_tree_num_tags" "noalloc"
355 let num_tags t = tree_num_tags t.doc
357 external tree_size : tree -> int = "caml_xml_tree_size" "noalloc"
358 let size t = tree_size t.doc
363 let rec loop left node acc_d total_d num_leaves =
365 (acc_d+total_d,if left then num_leaves+1 else num_leaves)
367 let d,td = loop true (tree_first_child tree node) (acc_d+1) total_d num_leaves in
368 loop false (tree_next_sibling tree node) (acc_d) d td
370 let a,b = loop true root 0 0 0
372 Logger.print err_formatter "Average depth: %f, number of leaves %i@\n@?" ((float_of_int a)/. (float_of_int b)) b
380 external hash : t -> int = "%identity"
381 external uid : t -> Uid.t = "%identity"
382 external equal : t -> t -> bool = "%eq"
383 external make : t -> int = "%identity"
384 external node : t -> int = "%identity"
385 external stats : unit -> unit = "%identity"
388 let to_ptset s = fold (Ptset.Int.add) s Ptset.Int.empty
392 Hashtbl.Make(struct type t = TagS.t * TagS.t
394 HASHINT2(Uid.to_int x.TagS.Node.id,
395 Uid.to_int y.TagS.Node.id)
402 Hashtbl.Make(struct type t = Tag.t * TagS.t
404 HASHINT2(x, Uid.to_int y.TagS.Node.id)
411 let add_cache = TagTSCache.create 1023
412 let union_cache = TSTSCache.create 1023
413 let subset_cache = TSTSCache.create 1023
416 TSTSCache.clear union_cache;
417 TSTSCache.clear subset_cache;
418 TagTSCache.clear add_cache
421 (x == y) || (x == TagS.empty) ||
422 if y == TagS.empty then false
426 TSTSCache.find subset_cache key
429 let z = TagS.subset x y in
430 TSTSCache.add subset_cache key z; z
432 let order ((x, y) as z) =
433 if x.TagS.Node.id <= y.TagS.Node.id then z
437 if _subset x y then y
438 else if _subset y x then x
440 let key = order (x, y) in
442 TSTSCache.find union_cache key
445 let z = TagS.union x y in
446 TSTSCache.add union_cache key z; z
451 TagTSCache.find add_cache key
454 let z = TagS.add t s in
455 TagTSCache.add add_cache key z;z
457 let child_sibling_labels tree =
458 let table_c = Array.create (tree_num_tags tree) TagS.empty in
459 let table_n = Array.copy table_c in
461 if node == nil then TagS.empty
463 let children = loop (tree_first_child tree node) in
464 let tag = tree_tag tree node in
466 let tc = table_c.(tag) in
467 if _subset children tc then ()
468 else table_c.(tag) <- _union tc children
470 let siblings = loop (tree_next_sibling tree node) in
472 let tn = table_n.(tag) in
473 if _subset siblings tn then ()
474 else table_n.(tag) <- _union tn siblings
481 let descendant_labels tree =
482 let table_d = Array.create (tree_num_tags tree) TagS.empty in
484 if node == nil then TagS.empty else
485 let d1 = loop (tree_first_child tree node) in
486 let d2 = loop (tree_next_sibling tree node) in
487 let tag = tree_tag tree node in
489 let td = table_d.(tag) in
490 if _subset d1 td then ()
491 else table_d.(tag) <- _union td d1;
493 _add tag (_union d1 d2)
498 let collect_labels tree =
499 let table_f = Array.create (tree_num_tags tree) TagS.empty in
500 let table_n = Array.copy table_f in
501 let table_c = Array.copy table_f in
502 let table_d = Array.copy table_f in
503 let rec loop node foll_siblings descendants followings =
504 if node == nil then foll_siblings, descendants, followings else
505 let tag = tree_tag tree node in
507 let tf = table_f.(tag) in
508 if _subset followings tf then ()
509 else table_f.(tag) <- _union tf followings in
511 let tn = table_n.(tag) in
512 if _subset foll_siblings tn then ()
513 else table_n.(tag) <- _union tn foll_siblings in
514 let children, n_descendants, n_followings =
515 loop (tree_last_child tree node) TagS.empty TagS.empty followings
518 let tc = table_c.(tag) in
519 if _subset children tc then ()
520 else table_c.(tag) <- _union tc children
523 let td = table_d.(tag) in
524 if _subset n_descendants td then ()
525 else table_d.(tag) <- _union td n_descendants
527 loop (tree_prev_sibling tree node)
528 (_add tag foll_siblings)
529 (_add tag (_union n_descendants descendants))
530 (_add tag n_followings)
532 ignore (loop root TagS.empty TagS.empty TagS.empty);
533 table_f, table_n, table_c, table_d
536 let is_nil t = t == nil
537 let is_node t = t != nil
538 let is_root t = t == root
541 Logger.print err_formatter "Initializing tag structure@\n";
542 let _ = Tag.init (mk_tag_ops t) in
543 Logger.print err_formatter "Starting tag table construction@\n";
544 let f, n, c, d = time collect_labels t ~msg:"Building tag relationship table" in
545 let c = Array.map TagS.to_ptset c in
546 let n = Array.map TagS.to_ptset n in
547 let f = Array.map TagS.to_ptset f in
548 let d = Array.map TagS.to_ptset d in
549 let () = clear_cache () in
550 let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
551 let elements = Ptset.Int.add Tag.document_node
552 (Ptset.Int.remove Tag.pcdata
553 (Ptset.Int.diff d.(Tag.document_node) attributes))
556 attributes = attributes;
557 attribute_array = Array.of_list (Ptset.Int.elements attributes);
567 let parse_xml_uri str = node_of_t (TreeBuilder.parse_file str)
568 let parse_xml_string str = node_of_t (TreeBuilder.parse_string str)
570 let size t = tree_size t.doc;;
572 let magic_string = "SXSI_INDEX"
573 let version_string = "3"
576 Unix.lseek fd 0 Unix.SEEK_CUR
578 let pr_pos fd = Logger.print err_formatter "At position %i@\n" (pos fd)
581 let sl = String.length s in
582 let ssl = Printf.sprintf "%020i" sl in
583 ignore (Unix.write fd ssl 0 20);
584 ignore (Unix.write fd s 0 (String.length s))
586 let rec really_read fd buffer start length =
587 if length <= 0 then () else
588 match Unix.read fd buffer start length with
589 0 -> raise End_of_file
590 | r -> really_read fd buffer (start + r) (length - r);;
593 let buffer = String.create 20 in
594 let _ = really_read fd buffer 0 20 in
595 let size = int_of_string buffer in
596 let buffer = String.create size in
597 let _ = really_read fd buffer 0 size in
600 let save_tag_table channel t =
601 let t = Array.map (fun s -> Array.of_list (Ptset.Int.elements s)) t in
602 Marshal.to_channel channel t []
605 let fd = Unix.openfile str [ Unix.O_WRONLY;Unix.O_TRUNC;Unix.O_CREAT] 0o644 in
606 let out_c = Unix.out_channel_of_descr fd in
607 let index_prefix = Filename.chop_suffix str ".srx" in
608 let _ = set_binary_mode_out out_c true in
609 output_string out_c magic_string;
610 output_char out_c '\n';
611 output_string out_c version_string;
612 output_char out_c '\n';
613 save_tag_table out_c t.children;
614 save_tag_table out_c t.siblings;
615 save_tag_table out_c t.descendants;
616 save_tag_table out_c t.followings;
617 (* we need to move the fd to the correct position *)
619 ignore (Unix.lseek fd (pos_out out_c) Unix.SEEK_SET);
620 tree_save t.doc fd index_prefix;
623 let load_tag_table channel =
624 let table : int array array = Marshal.from_channel channel in
625 Array.map (fun a -> Ptset.Int.from_list (Array.to_list a)) table
627 let load ?(sample=64) ?(load_text=true) str =
628 let fd = Unix.openfile str [ Unix.O_RDONLY ] 0o644 in
629 let in_c = Unix.in_channel_of_descr fd in
630 let index_prefix = Filename.chop_suffix str ".srx" in
631 let _ = set_binary_mode_in in_c true in
633 (let ms = input_line in_c in if ms <> magic_string then failwith "Invalid index file");
634 (let vs = input_line in_c in if vs <> version_string then failwith "Invalid version file");
635 let c = load_tag_table in_c in
636 let s = load_tag_table in_c in
637 let d = load_tag_table in_c in
638 let f = load_tag_table in_c in
641 let c, s, d, f = time ~msg:"Loading tag table"(load_table) () in
642 ignore(Unix.lseek fd (pos_in in_c) Unix.SEEK_SET);
643 let xml_tree = tree_load fd index_prefix load_text sample in
644 let () = Tag.init (Obj.magic xml_tree) in
645 let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
646 let elements = Ptset.Int.add Tag.document_node
647 (Ptset.Int.remove Tag.pcdata
648 (Ptset.Int.diff d.(Tag.document_node) attributes))
650 let tree = { doc = xml_tree;
651 attributes = attributes;
652 attribute_array = Array.of_list (Ptset.Int.elements attributes);
665 let equal a b = a == b
669 | i -> Printf.sprintf "Node (%i)" i
671 let dump_node t = nts (Node.to_int t)
675 type query_result = { bv : bit_vector;
679 external tree_flush : tree -> Unix.file_descr -> unit = "caml_xml_tree_flush"
680 let flush t fd = tree_flush t.doc fd
682 external text_prefix : tree -> string -> bool -> query_result = "caml_text_collection_prefix_bv"
683 let text_prefix t s b = text_prefix t.doc s b
685 external text_suffix : tree -> string -> bool -> query_result = "caml_text_collection_suffix_bv"
686 let text_suffix t s b = text_suffix t.doc s b
688 external text_equals : tree -> string -> bool -> query_result = "caml_text_collection_equals_bv"
689 let text_equals t s b = text_equals t.doc s b
691 external text_contains : tree -> string -> bool -> query_result = "caml_text_collection_contains_bv"
692 let text_contains t s b = text_contains t.doc s b
695 module Predicate = Hcons.Make (
698 type t = (_t -> node -> bool) ref
699 let hash t = Hashtbl.hash t
700 let equal t1 t2 = t1 == t2
703 let string_of_query query =
705 | `Prefix -> "starts-with"
706 | `Suffix -> "ends-with"
707 | `Equals -> "equals"
708 | `Contains -> "contains"
711 let query_fun = function
712 | `Prefix -> text_prefix
713 | `Suffix -> text_suffix
714 | `Equals -> text_equals
715 | `Contains -> text_contains
718 let _pred_cache = Hashtbl.create 17
720 let mk_pred query s =
721 let f = query_fun query in
722 let memo = ref (fun _ _ -> failwith "Undefined") in
723 memo := begin fun tree node ->
725 try Hashtbl.find _pred_cache (query,s) with
727 time ~count:1 ~msg:(Printf.sprintf "Computing text query %s(%s)"
728 (string_of_query query) s)
731 let bv = results.bv in
732 memo := begin fun _ n ->
733 bit_vector_unsafe_get bv (Node.to_int n)
735 bit_vector_unsafe_get bv (Node.to_int node)
740 let full_text_prefix t s = (text_prefix t s true).pos
742 let full_text_suffix t s = (text_suffix t s true).pos
744 let full_text_equals t s = (text_equals t s true).pos
746 let full_text_contains t s = (text_contains t s true).pos
748 let full_text_query q t s =
749 let res = (query_fun q) t s true in
750 Hashtbl.replace _pred_cache (q,s) res;