Add the node summary to the Tree interface.
[tatoo.git] / src / tree.ml
index 9ef78ce..a1cd6a1 100644 (file)
 (*  ../LICENSE.                                                        *)
 (*                                                                     *)
 (***********************************************************************)
-
-(*
-  Time-stamp: <Last modified on 2013-04-04 18:40:39 CEST by Kim Nguyen>
-*)
+open Misc
 
 (** The different kind of XML nodes and utility functions *)
 
 module NodeKind =
   struct
     type t =
-        Document | Element | Text | Comment | Attribute | ProcessingInstruction | Node
+      Document | Element | Text | Comment | Attribute
+    | ProcessingInstruction | Node
 
     let to_string =
       function
@@ -42,8 +40,48 @@ module NodeKind =
 end
 
 
+module NodeSummary =
+struct
+  (* Pack into an integer the result of the is_* and has_ predicates
+     for a given node *)
+  type t = int
+  let dummy = -1
+  (*
+    ...44443210
+    ...4444 -> kind
+    3 -> has_right
+    2 -> has_left
+    1 -> is_right
+    0 -> is_left
+  *)
+  let is_left (s : t) : bool =
+    s land 1 != 0
+
+  let is_right (s : t) : bool =
+    s land 0b10 != 0
+
+  let has_left (s : t) : bool =
+    s land 0b100 != 0
+
+  let has_right (s : t) : bool =
+    s land 0b1000 != 0
+
+  let kind (s : t) : NodeKind.t =
+    Obj.magic (s lsr 4)
+
+  let make is_left is_right has_left has_right kind =
+    (int_of_bool is_left) lor
+      ((int_of_bool is_right) lsl 1) lor
+      ((int_of_bool has_left) lsl 2) lor
+      ((int_of_bool has_right) lsl 3) lor
+      ((Obj.magic kind) lsl 4)
+end
+
+
 (** Signatures for trees *)
 
+exception Parse_error of string
+
 module type S =
 sig
   type node
@@ -106,10 +144,17 @@ sig
   val kind : t -> node -> NodeKind.t
   (** Returns the kind of the given node *)
 
+  val summary : t -> node -> NodeSummary.t
+  (** Returns the summary of the given node *)
+
   val preorder : t -> node -> int
-  (** Returns the position of a node in pre-order in the tree. The
-    root has preorder 0. [nil] has pre-order [-1].
+  (** [preorder t n] returns the pre-order position of [n] in [t].
+      [preodrder t (root t) == 0] and [preorder t nil < 0].
   *)
 
+  val by_preorder : t -> int -> node
+  (** [by_preorder t i] returns the node with preorder [i]
+  *)
   val print_node : Format.formatter -> node -> unit
+
 end