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 =
99 display_count parser_;
106 List.iter (fun (name, value) -> output_attr b name value) l;
110 let end_element_handler parser_ b t tag =
111 display_count parser_;
115 let character_data_handler parser_ _ t text =
116 display_count parser_;
117 Buffer.add_string t text
119 let create_parser () =
120 let buf = Buffer.create 512 in
121 let build = create () in
122 let parser_ = Expat.parser_create ~encoding:None in
126 Logger.print Format.err_formatter "Finished parsing@\n";
127 Logger.print Format.err_formatter "Starting index construction@\n";
128 let r = close_document build in
129 Logger.print Format.err_formatter "Finished index construction@\n";
132 Expat.set_start_element_handler parser_ (start_element_handler parser_ build buf);
133 Expat.set_end_element_handler parser_ (end_element_handler parser_ build buf);
134 Expat.set_character_data_handler parser_ (character_data_handler parser_ build buf);
135 Logger.print Format.err_formatter "Started parsing@\n";
136 open_document build !Options.sample_factor !Options.disable_text_collection !Options.text_index_type;
141 let parser_, finalizer = create_parser () in
142 Expat.parse parser_ s;
145 let parse_file file =
146 let in_chan = open_in file in
147 let buffer = String.create 4096 in
148 let parser_, finalizer = create_parser () in
152 let read = input in_chan buffer 0 4096 in
153 if read == 0 then raise End_of_file else
154 Expat.parse_sub parser_ buffer 0 read;
158 | End_of_file -> close_in in_chan
168 type bit_vector = string
170 external bool_of_int : int -> bool = "%identity"
171 external int_of_bool : bool -> int = "%identity"
173 let bit_vector_unsafe_get v i =
175 (((Char.code (String.unsafe_get v (i lsr 3))) lsr (i land 7)) land 1)
176 let chr (c:int) : char = Obj.magic (c land 0xff)
177 let bit_vector_unsafe_set v i b =
179 let c = Char.code v.[j] in
180 let bit = int_of_bool b in
181 let mask = bit lsl (i land 7) in
182 if b then v.[j] <- chr (c lor mask) else v.[j] <- (chr (c land (lnot mask)))
184 let bit_vector_create n =
185 let len = if n <= 0 then 0 else (n - 1) / 8 + 1 in
186 String.make len '\000'
190 elements: Ptset.Int.t;
191 attributes: Ptset.Int.t;
192 attribute_array : Tag.t array;
193 children : Ptset.Int.t array;
194 siblings : Ptset.Int.t array;
195 descendants: Ptset.Int.t array;
196 followings: Ptset.Int.t array;
200 let tag_operations t = mk_tag_ops t.doc
202 external parse_xml_uri : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_uri"
203 external parse_xml_string : string -> int -> bool -> bool -> int -> tree = "caml_call_shredder_string"
205 external tree_print_xml_fast3 : tree -> [`Tree ] Node.t -> Unix.file_descr -> unit = "caml_xml_tree_print"
206 let print_xml t n fd =
207 tree_print_xml_fast3 t.doc n fd
210 external tree_save : tree -> Unix.file_descr -> string -> unit = "caml_xml_tree_save"
211 external tree_load : Unix.file_descr -> string -> bool -> int -> tree = "caml_xml_tree_load"
213 external nullt : unit -> 'a Node.t = "caml_xml_tree_nullt"
215 let nil : [`Tree ] Node.t = Node.nil
216 let root : [`Tree ] Node.t = Node.null
220 external unordered_set_alloc : int -> unordered_set = "caml_unordered_set_alloc"
221 external unordered_set_length : unordered_set -> int = "caml_unordered_set_length"
222 external unordered_set_insert : unordered_set -> int -> unit = "caml_unordered_set_set" "noalloc"
224 module HPtset = Hashtbl.Make(Ptset.Int)
226 let vector_htbl = HPtset.create MED_H_SIZE
228 let unordered_set_of_set s =
230 HPtset.find vector_htbl s
233 let v = unordered_set_alloc (Ptset.Int.cardinal s) in
234 let _ = Ptset.Int.iter (fun e -> unordered_set_insert v e) s in
235 HPtset.add vector_htbl s v; v
237 let ptset_to_vector = unordered_set_of_set
239 (** tree interface *)
241 external tree_root : tree -> [`Tree] Node.t = "caml_xml_tree_root" "noalloc"
244 external tree_first_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_child" "noalloc"
245 let first_child t n = tree_first_child t.doc n
247 external tree_first_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_first_element" "noalloc"
248 let first_element t n = tree_first_element t.doc n
250 external tree_tagged_child : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_child" "noalloc"
251 let tagged_child t n tag = tree_tagged_child t.doc n tag
253 external tree_select_child : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_child" "noalloc"
254 let select_child t n tag_set = tree_select_child t.doc n tag_set
256 external tree_last_child : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_last_child" "noalloc"
257 let last_child t n = tree_last_child t.doc n
260 external tree_next_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_sibling" "noalloc"
261 let next_sibling t n = tree_next_sibling t.doc n
263 external tree_next_element : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_next_element" "noalloc"
264 let next_element t n = tree_next_element t.doc n
267 external tree_tagged_sibling : tree -> [`Tree] Node.t -> Tag.t -> [`Tree] Node.t = "caml_xml_tree_tagged_sibling" "noalloc"
268 let tagged_sibling t n tag = tree_tagged_sibling t.doc n tag
271 external tree_select_sibling : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_sibling" "noalloc"
272 let select_sibling t n tag_set = tree_select_sibling t.doc n tag_set
274 external tree_prev_sibling : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_prev_sibling" "noalloc"
275 let prev_sibling t n = tree_prev_sibling t.doc n
279 external tree_tagged_descendant : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_descendant" "noalloc"
280 let tagged_descendant t n tag = tree_tagged_descendant t.doc n tag
282 external tree_tagged_next : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_next" "noalloc"
283 let tagged_next t n tag = tree_tagged_next t.doc n tag
285 external tree_select_descendant : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t = "caml_xml_tree_select_descendant" "noalloc"
286 let select_descendant t n tag_set = tree_select_descendant t.doc n tag_set
288 external tree_tagged_following_before : tree -> [`Tree ] Node.t -> Tag.t -> [`Tree ] Node.t -> [`Tree ] Node.t = "caml_xml_tree_tagged_following_before" "noalloc"
289 let tagged_following_before t n tag ctx = tree_tagged_following_before t.doc n tag ctx
291 external tree_select_following_before : tree -> [`Tree ] Node.t -> unordered_set -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_select_following_before" "noalloc"
292 let select_following_before t n tag_set ctx = tree_select_following_before t.doc n tag_set ctx
294 external tree_parent : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_parent" "noalloc"
295 let parent t n = tree_parent t.doc n
297 external tree_tag : tree -> [`Tree] Node.t -> Tag.t = "caml_xml_tree_tag" "noalloc"
298 let tag t n = tree_tag t.doc n
300 external tree_is_first_child : tree -> [ `Tree ] Node.t -> bool = "caml_xml_tree_is_first_child" "noalloc"
301 let is_first_child t n = tree_is_first_child t.doc n
303 external tree_is_right_descendant : tree -> [ `Tree ] Node.t -> [`Tree] Node.t -> bool =
304 "caml_xml_tree_is_right_descendant" "noalloc"
306 let is_right_descendant t n1 n2 = tree_is_right_descendant t.doc n1 n2
309 let node_tags t = Ptset.Int.add Tag.document_node t.descendants.(Tag.document_node)
311 let attribute_tags t = t.attributes
313 let element_tags t = t.elements
316 t.children.(tag), t.descendants.(tag), t.siblings.(tag), t.followings.(tag)
319 let dump_tag_table t =
321 let printer ppf set =
322 Logger.print ppf "%s: %a"
323 (Tag.to_string !tag) TagSet.print (TagSet.inj_positive set);
326 let set_printer msg set =
328 Logger.print err_formatter "%s :@\n" msg;
329 Pretty.pp_print_array ~sep:pp_force_newline printer err_formatter set;
330 Logger.print err_formatter "-----------------------------@\n";
332 set_printer "Child tags" t.children;
333 set_printer "Descendant tags" t.descendants;
334 set_printer "Sibling tags" t.siblings;
335 set_printer "Following tags" t.followings
337 external tree_subtree_tags : tree -> [`Tree] Node.t -> Tag.t -> int = "caml_xml_tree_subtree_tags" "noalloc"
338 let subtree_tags t n tag = tree_subtree_tags t.doc n tag
340 external tree_subtree_size : tree -> [`Tree] Node.t -> int = "caml_xml_tree_subtree_size" "noalloc"
341 let subtree_size t n = tree_subtree_size t.doc n
343 let subtree_elements t node =
344 let size = tree_subtree_size t.doc node - 1 in
346 else let size = size - (tree_subtree_tags t.doc node Tag.pcdata) in
347 if size < 2 then size else
348 let acc = ref size in
349 for i = 0 to Array.length t.attribute_array - 1 do
350 acc := !acc - tree_subtree_tags t.doc node t.attribute_array.(i)
354 external tree_closing : tree -> [`Tree] Node.t -> [`Tree] Node.t = "caml_xml_tree_closing" "noalloc"
355 let closing t n = tree_closing t.doc n
357 external tree_num_tags : tree -> int = "caml_xml_tree_num_tags" "noalloc"
358 let num_tags t = tree_num_tags t.doc
360 external tree_size : tree -> int = "caml_xml_tree_size" "noalloc"
361 let size t = tree_size t.doc
366 let rec loop left node acc_d total_d num_leaves =
368 (acc_d+total_d,if left then num_leaves+1 else num_leaves)
370 let d,td = loop true (tree_first_child tree node) (acc_d+1) total_d num_leaves in
371 loop false (tree_next_sibling tree node) (acc_d) d td
373 let a,b = loop true root 0 0 0
375 Logger.print err_formatter "Average depth: %f, number of leaves %i@\n@?" ((float_of_int a)/. (float_of_int b)) b
383 external hash : t -> int = "%identity"
384 external uid : t -> Uid.t = "%identity"
385 external equal : t -> t -> bool = "%eq"
386 external make : t -> int = "%identity"
387 external node : t -> int = "%identity"
388 external stats : unit -> unit = "%identity"
391 let to_ptset s = fold (Ptset.Int.add) s Ptset.Int.empty
395 Hashtbl.Make(struct type t = TagS.t * TagS.t
397 HASHINT2(Uid.to_int x.TagS.Node.id,
398 Uid.to_int y.TagS.Node.id)
405 Hashtbl.Make(struct type t = Tag.t * TagS.t
407 HASHINT2(x, Uid.to_int y.TagS.Node.id)
414 let add_cache = TagTSCache.create 1023
415 let union_cache = TSTSCache.create 1023
416 let subset_cache = TSTSCache.create 1023
419 TSTSCache.clear union_cache;
420 TSTSCache.clear subset_cache;
421 TagTSCache.clear add_cache
424 (x == y) || (x == TagS.empty) ||
425 if y == TagS.empty then false
429 TSTSCache.find subset_cache key
432 let z = TagS.subset x y in
433 TSTSCache.add subset_cache key z; z
435 let order ((x, y) as z) =
436 if x.TagS.Node.id <= y.TagS.Node.id then z
440 if _subset x y then y
441 else if _subset y x then x
443 let key = order (x, y) in
445 TSTSCache.find union_cache key
448 let z = TagS.union x y in
449 TSTSCache.add union_cache key z; z
454 TagTSCache.find add_cache key
457 let z = TagS.add t s in
458 TagTSCache.add add_cache key z;z
460 let child_sibling_labels tree =
461 let table_c = Array.create (tree_num_tags tree) TagS.empty in
462 let table_n = Array.copy table_c in
464 if node == nil then TagS.empty
466 let children = loop (tree_first_child tree node) in
467 let tag = tree_tag tree node in
469 let tc = table_c.(tag) in
470 if _subset children tc then ()
471 else table_c.(tag) <- _union tc children
473 let siblings = loop (tree_next_sibling tree node) in
475 let tn = table_n.(tag) in
476 if _subset siblings tn then ()
477 else table_n.(tag) <- _union tn siblings
484 let descendant_labels tree =
485 let table_d = Array.create (tree_num_tags tree) TagS.empty in
487 if node == nil then TagS.empty else
488 let d1 = loop (tree_first_child tree node) in
489 let d2 = loop (tree_next_sibling tree node) in
490 let tag = tree_tag tree node in
492 let td = table_d.(tag) in
493 if _subset d1 td then ()
494 else table_d.(tag) <- _union td d1;
496 _add tag (_union d1 d2)
501 let collect_labels tree =
502 let table_f = Array.create (tree_num_tags tree) TagS.empty in
503 let table_n = Array.copy table_f in
504 let table_c = Array.copy table_f in
505 let table_d = Array.copy table_f in
506 let rec loop node foll_siblings descendants followings =
507 if node == nil then foll_siblings, descendants, followings else
508 let tag = tree_tag tree node in
510 let tf = table_f.(tag) in
511 if _subset followings tf then ()
512 else table_f.(tag) <- _union tf followings in
514 let tn = table_n.(tag) in
515 if _subset foll_siblings tn then ()
516 else table_n.(tag) <- _union tn foll_siblings in
517 let children, n_descendants, n_followings =
518 loop (tree_last_child tree node) TagS.empty TagS.empty followings
521 let tc = table_c.(tag) in
522 if _subset children tc then ()
523 else table_c.(tag) <- _union tc children
526 let td = table_d.(tag) in
527 if _subset n_descendants td then ()
528 else table_d.(tag) <- _union td n_descendants
530 loop (tree_prev_sibling tree node)
531 (_add tag foll_siblings)
532 (_add tag (_union n_descendants descendants))
533 (_add tag n_followings)
535 ignore (loop root TagS.empty TagS.empty TagS.empty);
536 table_f, table_n, table_c, table_d
539 let is_nil t = t == nil
540 let is_node t = t != nil
541 let is_root t = t == root
544 Logger.print err_formatter "Initializing tag structure@\n";
545 let _ = Tag.init (mk_tag_ops t) in
546 Logger.print err_formatter "Starting tag table construction@\n";
547 let f, n, c, d = time collect_labels t ~msg:"Building tag relationship table" in
548 let c = Array.map TagS.to_ptset c in
549 let n = Array.map TagS.to_ptset n in
550 let f = Array.map TagS.to_ptset f in
551 let d = Array.map TagS.to_ptset d in
552 let () = clear_cache () in
553 let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
554 let elements = Ptset.Int.add Tag.document_node
555 (Ptset.Int.remove Tag.pcdata
556 (Ptset.Int.diff d.(Tag.document_node) attributes))
559 attributes = attributes;
560 attribute_array = Array.of_list (Ptset.Int.elements attributes);
570 let parse_xml_uri str = node_of_t (TreeBuilder.parse_file str)
571 let parse_xml_string str = node_of_t (TreeBuilder.parse_string str)
573 let size t = tree_size t.doc;;
575 let magic_string = "SXSI_INDEX"
576 let version_string = "3"
579 Unix.lseek fd 0 Unix.SEEK_CUR
581 let pr_pos fd = Logger.print err_formatter "At position %i@\n" (pos fd)
584 let sl = String.length s in
585 let ssl = Printf.sprintf "%020i" sl in
586 ignore (Unix.write fd ssl 0 20);
587 ignore (Unix.write fd s 0 (String.length s))
589 let rec really_read fd buffer start length =
590 if length <= 0 then () else
591 match Unix.read fd buffer start length with
592 0 -> raise End_of_file
593 | r -> really_read fd buffer (start + r) (length - r);;
596 let buffer = String.create 20 in
597 let _ = really_read fd buffer 0 20 in
598 let size = int_of_string buffer in
599 let buffer = String.create size in
600 let _ = really_read fd buffer 0 size in
603 let save_tag_table channel t =
604 let t = Array.map (fun s -> Array.of_list (Ptset.Int.elements s)) t in
605 Marshal.to_channel channel t []
608 let fd = Unix.openfile str [ Unix.O_WRONLY;Unix.O_TRUNC;Unix.O_CREAT] 0o644 in
609 let out_c = Unix.out_channel_of_descr fd in
610 let index_prefix = Filename.chop_suffix str ".srx" in
611 let _ = set_binary_mode_out out_c true in
612 output_string out_c magic_string;
613 output_char out_c '\n';
614 output_string out_c version_string;
615 output_char out_c '\n';
616 save_tag_table out_c t.children;
617 save_tag_table out_c t.siblings;
618 save_tag_table out_c t.descendants;
619 save_tag_table out_c t.followings;
620 (* we need to move the fd to the correct position *)
622 ignore (Unix.lseek fd (pos_out out_c) Unix.SEEK_SET);
623 tree_save t.doc fd index_prefix;
626 let load_tag_table channel =
627 let table : int array array = Marshal.from_channel channel in
628 Array.map (fun a -> Ptset.Int.from_list (Array.to_list a)) table
630 let load ?(sample=64) ?(load_text=true) str =
631 let fd = Unix.openfile str [ Unix.O_RDONLY ] 0o644 in
632 let in_c = Unix.in_channel_of_descr fd in
633 let index_prefix = Filename.chop_suffix str ".srx" in
634 let _ = set_binary_mode_in in_c true in
636 (let ms = input_line in_c in if ms <> magic_string then failwith "Invalid index file");
637 (let vs = input_line in_c in if vs <> version_string then failwith "Invalid version file");
638 let c = load_tag_table in_c in
639 let s = load_tag_table in_c in
640 let d = load_tag_table in_c in
641 let f = load_tag_table in_c in
644 let c, s, d, f = time ~msg:"Loading tag table"(load_table) () in
645 ignore(Unix.lseek fd (pos_in in_c) Unix.SEEK_SET);
646 let xml_tree = tree_load fd index_prefix load_text sample in
647 let () = Tag.init (Obj.magic xml_tree) in
648 let attributes = Ptset.Int.add Tag.attribute d.(Tag.attribute) in
649 let elements = Ptset.Int.add Tag.document_node
650 (Ptset.Int.remove Tag.pcdata
651 (Ptset.Int.diff d.(Tag.document_node) attributes))
653 let tree = { doc = xml_tree;
654 attributes = attributes;
655 attribute_array = Array.of_list (Ptset.Int.elements attributes);
668 let equal a b = a == b
672 | i -> Printf.sprintf "Node (%i)" i
674 let dump_node t = nts (Node.to_int t)
678 type query_result = { bv : bit_vector;
682 external tree_flush : tree -> Unix.file_descr -> unit = "caml_xml_tree_flush"
683 let flush t fd = tree_flush t.doc fd
685 external text_prefix : tree -> string -> bool -> query_result = "caml_text_collection_prefix_bv"
686 let text_prefix t s b = text_prefix t.doc s b
688 external text_suffix : tree -> string -> bool -> query_result = "caml_text_collection_suffix_bv"
689 let text_suffix t s b = text_suffix t.doc s b
691 external text_equals : tree -> string -> bool -> query_result = "caml_text_collection_equals_bv"
692 let text_equals t s b = text_equals t.doc s b
694 external text_contains : tree -> string -> bool -> query_result = "caml_text_collection_contains_bv"
695 let text_contains t s b = text_contains t.doc s b
698 module Predicate = Hcons.Make (
701 type t = (_t -> node -> bool) ref
702 let hash t = Hashtbl.hash t
703 let equal t1 t2 = t1 == t2
706 let string_of_query query =
708 | `Prefix -> "starts-with"
709 | `Suffix -> "ends-with"
710 | `Equals -> "equals"
711 | `Contains -> "contains"
714 let query_fun = function
715 | `Prefix -> text_prefix
716 | `Suffix -> text_suffix
717 | `Equals -> text_equals
718 | `Contains -> text_contains
721 let _pred_cache = Hashtbl.create 17
723 let mk_pred query s =
724 let f = query_fun query in
725 let memo = ref (fun _ _ -> failwith "Undefined") in
726 memo := begin fun tree node ->
728 try Hashtbl.find _pred_cache (query,s) with
730 time ~count:1 ~msg:(Printf.sprintf "Computing text query %s(%s)"
731 (string_of_query query) s)
734 let bv = results.bv in
735 memo := begin fun _ n ->
736 bit_vector_unsafe_get bv (Node.to_int n)
738 bit_vector_unsafe_get bv (Node.to_int node)
743 let full_text_prefix t s = (text_prefix t s true).pos
745 let full_text_suffix t s = (text_suffix t s true).pos
747 let full_text_equals t s = (text_equals t s true).pos
749 let full_text_contains t s = (text_contains t s true).pos
751 let full_text_query q t s =
752 let res = (query_fun q) t s true in
753 Hashtbl.replace _pred_cache (q,s) res;