8671baeba3abb37b4cef85bf522ce4f0f3536840
[SXSI/XMLTree.git] / XMLTree.h
1 /******************************************************************************\r
2  *   Copyright (C) 2008 by Diego Arroyuelo                                    *\r
3  *   Interface for the in-memory XQuery/XPath engine                          *\r
4  *                                                                            *\r
5  *   This program is free software; you can redistribute it and/or modify     *\r
6  *   it under the terms of the GNU Lesser General Public License as published *\r
7  *   by the Free Software Foundation; either version 2 of the License, or     *\r
8  *   (at your option) any later version.                                      *\r
9  *                                                                            *\r
10  *   This program is distributed in the hope that it will be useful,          *\r
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of           *\r
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *\r
13  *   GNU Lesser General Public License for more details.                      *\r
14  *                                                                            *\r
15  *   You should have received a copy of the GNU Lesser General Public License *\r
16  *   along with this program; if not, write to the                            *\r
17  *   Free Software Foundation, Inc.,                                          *\r
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.                *\r
19  ******************************************************************************/\r
20 \r
21 #ifndef XMLTREE_H_\r
22 #define XMLTREE_H_\r
23 \r
24 \r
25 #include <unordered_set>\r
26 #include <unordered_map>\r
27 #include <sstream>\r
28 #include "TextCollection/TextCollectionBuilder.h"\r
29 \r
30 #undef W\r
31 #undef WW\r
32 #undef Wminusone\r
33 \r
34 #include "bp.h"\r
35 #include <libcds/includes/basics.h>\r
36 #include <static_bitsequence.h>\r
37 #include <alphabet_mapper.h>\r
38 #include <static_sequence.h>\r
39 using SXSI::TextCollection;\r
40 using SXSI::TextCollectionBuilder;\r
41 \r
42 \r
43 // this constant is used to efficiently compute the child operation in the tree\r
44 #define OPTD 10\r
45 \r
46 #define NULLT -1\r
47 \r
48 #define PERM_SAMPLE 10\r
49 \r
50 \r
51 typedef int treeNode;\r
52 typedef int TagType; \r
53 typedef int DocID;  \r
54 \r
55 typedef struct {\r
56    int min;\r
57    int max;\r
58 } range;\r
59 \r
60 // Encoding of the XML Document :\r
61 // The following TAGs and IDs are fixed, "" is the tag of the root.\r
62 // a TextNode is represented by a leaf <<$>></<$>> The DocId in the TextCollection\r
63 // of that leaf is kept in a bit sequence.\r
64 // a TextNode below an attribute is likewise represented by a leaf <<@$>><</@$>>\r
65 // An element <e a1="v1" a2="v2" ... an="vn" > ...</e> the representation is:\r
66 // <e><<@>> <<@>a1> <<$@>>DocID(v1)</<$@>></<@>a1> ... </<@>> .... </e>\r
67 // Hence the attributes (if any) are always below the first child of their element,\r
68 // as the children of a fake node <@>.\r
69 \r
70 \r
71 #define DOCUMENT_OPEN_TAG ""\r
72 #define DOCUMENT_TAG_ID 0\r
73 #define ATTRIBUTE_OPEN_TAG "<@>"\r
74 #define ATTRIBUTE_TAG_ID 1\r
75 #define PCDATA_OPEN_TAG "<$>"\r
76 #define PCDATA_TAG_ID 2\r
77 #define ATTRIBUTE_DATA_OPEN_TAG "<@$>"\r
78 #define ATTRIBUTE_DATA_TAG_ID 3\r
79 #define CLOSING_TAG   "</>"\r
80 #define CLOSING_TAG_ID 4\r
81 #define DOCUMENT_CLOSE_TAG "/"\r
82 #define ATTRIBUTE_CLOSE_TAG "/<@>"\r
83 #define PCDATA_CLOSE_TAG "/<$>"\r
84 #define ATTRIBUTE_DATA_CLOSE_TAG "/<@$>"\r
85 \r
86 \r
87 typedef std::unordered_set<int> TagIdSet;\r
88 typedef std::unordered_map<std::string,int> TagIdMap;\r
89 typedef TagIdMap::const_iterator TagIdMapIT;\r
90 \r
91 #define REGISTER_TAG(v,h,t) do { (h)->insert(std::make_pair((t),(v)->size()));\\r
92     (v)->push_back(t); } while (false)\r
93 \r
94 \r
95 // returns NULLT if the test is true\r
96 #define NULLT_IF(x)  do { if (x) return NULLT; } while (0)\r
97 \r
98 // Direct calls to sarray library\r
99 \r
100 static inline int fast_find_close(bp *b,int s)\r
101 {\r
102   return fwd_excess(b,s,-1);\r
103 }\r
104 \r
105 static int fast_inspect(bp* Par,treeNode i)\r
106 {\r
107   int j,l;\r
108   j = i >> logD;\r
109   l = i & (D-1);\r
110   return (Par->B[j] >> (D-1-l)) & 1;\r
111 }\r
112 \r
113 static treeNode fast_first_child(bp *Par, treeNode x)\r
114 {\r
115   x = x+1;\r
116   return (fast_inspect(Par,x) == OP) ? x : NULLT;\r
117 }\r
118 \r
119 static treeNode fast_next_sibling(bp* Par,treeNode x)\r
120 {\r
121   x = fast_find_close(Par,x)+1;\r
122   return (fast_inspect(Par,x) == OP) ? x : NULLT;\r
123 }\r
124 \r
125 static bool fast_is_ancestor(bp * Par,treeNode x,treeNode y){\r
126   return (x <= y) && ((x==0) || (y <= fast_find_close(Par,x)));\r
127 }\r
128 \r
129 // tag position -> tree node\r
130 static treeNode tagpos2node(int t) \r
131  {\r
132     return (treeNode) t;\r
133  }\r
134 // tree node -> tag position\r
135 static int node2tagpos(treeNode x) \r
136 {\r
137   return (int)x;\r
138 }\r
139 \r
140 \r
141 class XMLTreeBuilder;\r
142 \r
143 class XMLTree {\r
144 \r
145   // Only the builder can access the constructor\r
146   friend class XMLTreeBuilder;\r
147 \r
148  private:\r
149    /** Balanced parentheses representation of the tree */\r
150    bp *Par;\r
151  \r
152    /** Mapping from tag identifer to tag name */  \r
153    std::vector<std::string> *TagName;\r
154    TagIdMap * tIdMap;\r
155   \r
156    /** Bit vector indicating with a 1 the positions of the non-empty texts. */\r
157    static_bitsequence *EBVector;  \r
158                       \r
159    /** Tag sequence represented with a data structure for rank and select */\r
160    static_sequence *Tags;\r
161    uint * tags_fix;\r
162    uint tags_blen, tags_len;\r
163 \r
164    /** The texts in the XML document */\r
165    TextCollection *Text;\r
166 \r
167    // Allows to disable the TextCollection for benchmarkin purposes\r
168    bool disable_tc;\r
169    \r
170    FILE* stream;\r
171    int   stream_fd; \r
172    std::string * buffer;\r
173    void myfputs(const char* s, FILE * fp){\r
174      buffer->append(s);\r
175      if (buffer->size() >= 100000){\r
176        fputs(buffer->c_str(),fp);\r
177        buffer->clear();\r
178      };\r
179 \r
180    }\r
181    void myfputc(const char c, FILE*fp){\r
182      buffer->append(1,c);\r
183      if (buffer->size() >= 100000){\r
184        fputs(buffer->c_str(),fp);\r
185        buffer->clear();\r
186      };\r
187    }\r
188    void mybufferflush(FILE* fp){\r
189      fputs(buffer->c_str(), fp);\r
190      buffer->clear();\r
191    }\r
192 \r
193    size_t myfprintf(const char* s, FILE * fp){\r
194      if (s == NULL)\r
195        return 0;\r
196      size_t i = buffer->size();\r
197      buffer->append(s);\r
198      size_t j = buffer->size();\r
199      if (buffer->size() >= 100000){\r
200        fputs(buffer->c_str(),fp);\r
201        buffer->clear();\r
202      };\r
203      return (j-i);\r
204    }\r
205 \r
206    void PrintNode(treeNode n, int fd);\r
207    /** Data structure constructors */\r
208    XMLTree(){ buffer = 0;};\r
209 \r
210    // non const pointer are freed by this method.\r
211    XMLTree( pb * const par, uint npar,  std::vector<std::string> * const TN,  TagIdMap * const tim, uint *empty_texts_bmp, TagType *tags,\r
212            TextCollection * const TC, bool dis_tc);\r
213 \r
214 public: \r
215    /** Data structure destructor */\r
216    ~XMLTree();\r
217    \r
218    /** root(): returns the tree root. */\r
219    treeNode Root() { return 0; }\r
220 \r
221    /** Size() :  Number of parenthesis */\r
222    unsigned int Size(){\r
223      return tags_len/2;\r
224    }\r
225 \r
226    /** SubtreeSize(x): the number of nodes (and attributes) in the subtree of \r
227     * node x. */\r
228    int SubtreeSize(treeNode x);\r
229   \r
230    /** SubtreeTags(x,tag): the number of occurrences of tag within the subtree \r
231     * of node x. */\r
232    int SubtreeTags(treeNode x, TagType tag);\r
233    \r
234    /** SubtreeElements(x) of element nodes in the subtree of x\r
235     */\r
236    int SubtreeElements(treeNode x);\r
237 \r
238    /** IsLeaf(x): returns whether node x is leaf or not. In the succinct \r
239     * representation this is just a bit inspection. */\r
240 \r
241    bool IsLeaf(treeNode x);\r
242 \r
243    /** IsAncestor(x,y): returns whether node x is ancestor of node y. */\r
244 \r
245    bool IsAncestor(treeNode x, treeNode y);\r
246   \r
247    /** IsChild(x,y): returns whether node x is parent of node y. */\r
248    bool IsChild(treeNode x, treeNode y);\r
249 \r
250    /** IsFirstChild(x): returns whether node x is the first child of its parent. */\r
251    /* OCAML */\r
252    bool IsFirstChild(treeNode x) { \r
253            return ((x != NULLT)&&(x==Root() || prev_sibling(Par,x) == (treeNode)-1));\r
254    };\r
255      \r
256    /** NumChildren(x): number of children of node x. Constant time with the \r
257     * data structure of Sadakane. */\r
258    int NumChildren(treeNode x);\r
259 \r
260    /** ChildNumber(x): returns i if node x is the i-th children of its \r
261     * parent. */\r
262    int ChildNumber(treeNode x);\r
263 \r
264    /** Depth(x): depth of node x, a simple binary rank on the parentheses \r
265     * sequence. */\r
266    int Depth(treeNode x);\r
267    \r
268    /** Preorder(x): returns the preorder number of node x, just regarding tree \r
269     * nodes (and not texts). */ \r
270    int Preorder(treeNode x);\r
271    \r
272    /** Postorder(x): returns the postorder number of node x, just regarding \r
273     * tree nodes (and not texts). */\r
274    int Postorder(treeNode x);\r
275       \r
276 \r
277    /** DocIds(x): returns the range (i.e., a pair of integers) of document \r
278     * identifiers that descend from node x. */\r
279    range DocIds(treeNode x);\r
280 \r
281    /** Parent(x): returns the parent node of node x. */\r
282    treeNode Parent(treeNode x) {           \r
283     if (x == Root())\r
284       return NULLT;\r
285     else\r
286       return parent(Par, x);\r
287    };\r
288    /* Assumes x is neither 0 nor -1 */\r
289    \r
290    /** Child(x,i): returns the i-th child of node x, assuming it exists. */   \r
291    treeNode Child(treeNode x, int i);\r
292 \r
293 \r
294 \r
295    /** LastChild(x): returns the last child of node x.  */\r
296    treeNode LastChild(treeNode x);\r
297    \r
298 \r
299 \r
300    /** PrevSibling(x): returns the previous sibling of node x, assuming it \r
301     * exists. */\r
302 \r
303    treeNode PrevSibling(treeNode x);\r
304    \r
305    /** TaggedChild(x,tag): returns the first child of node x tagged tag, or \r
306     * NULLT if there is none. Because of the balanced-parentheses representation \r
307     * of the tree, this operation is not supported efficiently, just iterating \r
308     * among the children of node x until finding the desired child. */\r
309    treeNode TaggedChild(treeNode x, TagType tag);\r
310    \r
311    treeNode SelectChild(treeNode x, TagIdSet * tags);\r
312 \r
313    /** TaggedFollowingSibling(x,tag): returns the first sibling of node x tagged tag, or \r
314     *  NULLT if there is none. */\r
315    treeNode TaggedFollowingSibling(treeNode x, TagType tag);\r
316    \r
317    treeNode SelectFollowingSibling(treeNode x, TagIdSet * tags);\r
318 \r
319 \r
320 \r
321 \r
322   treeNode SelectDescendant(treeNode x, TagIdSet * tags);\r
323 \r
324    /** TaggedPrec(x,tag): returns the first node tagged tag with smaller \r
325     * preorder than x and not an ancestor of x. Returns NULLT if there \r
326     * is none. */\r
327    treeNode TaggedPreceding(treeNode x, TagType tag);\r
328   \r
329    /** TaggedFoll(x,tag): returns the first node tagged tag with larger \r
330     * preorder than x and not in the subtree of x. Returns NULLT if there \r
331     * is none. */\r
332    treeNode TaggedFollowing(treeNode x, TagType tag);\r
333 \r
334 \r
335 \r
336    treeNode SelectFollowingBelow(treeNode x, TagIdSet * tags, treeNode ancestor);\r
337 \r
338    treeNode TaggedFollowingBefore(treeNode x, TagType tag,treeNode closing);\r
339 \r
340    treeNode SelectFollowingBefore(treeNode x, TagIdSet * tags, treeNode closing);\r
341 \r
342    /** TaggedAncestor(x, tag): returns the closest ancestor of x tagged \r
343      * tag. Return NULLT is there is none. */\r
344    treeNode TaggedAncestor(treeNode x, TagType tag);\r
345  \r
346    /** PrevText(x): returns the document identifier of the text to the left of \r
347     * node x, or NULLT if x is the root node. */\r
348    DocID PrevText(treeNode x);\r
349    \r
350    /** NextText(x): returns the document identifier of the text to the right of \r
351     * node x, or NULLT if x is the root node. */\r
352    DocID NextText(treeNode x);\r
353    \r
354    /** MyText(x): returns the document identifier of the text below node x, or \r
355     * NULLT if x is not a leaf node. */\r
356    DocID MyText(treeNode x);\r
357    DocID MyTextUnsafe(treeNode x);\r
358 \r
359    /** TextXMLId(d): returns the preorder of document with identifier d in the \r
360     * tree consisting of all tree nodes and all text nodes. */\r
361    int TextXMLId(DocID d);\r
362    \r
363    /** NodeXMLId(x): returns the preorder of node x in the tree consisting of \r
364     * all tree nodes and all text nodes. */\r
365    int NodeXMLId(treeNode x);\r
366    \r
367    /** ParentNode(d): returns the parent node of document identifier d. */\r
368    treeNode ParentNode(DocID d);\r
369    \r
370    treeNode PrevNode(DocID d);\r
371 \r
372    /** GetTagId(tagname): returns the tag identifier corresponding to a given \r
373     * tag name. Returns NULLT in case that the tag name does not exists. */\r
374    TagType GetTagId(unsigned char *tagname);\r
375 \r
376    /** GetTagName(tagid): returns the tag name of a given tag identifier. \r
377     * Returns NULL in case that the tag identifier is not valid.*/\r
378    unsigned char *GetTagName(TagType tagid);\r
379 \r
380    /** GetTagName(tagid): returns the tag name of a given tag identifier.     \r
381     *  The result is just a reference and should not be freed by the caller.\r
382     */\r
383    const unsigned char *GetTagNameByRef(TagType tagid);\r
384 \r
385    /** RegisterTag adds a new tag to the tag collection this is needed\r
386     * if the query contains a tag which is not in the document, we need\r
387     * to give this new tag a fresh id and store it somewhere. A logical\r
388     * choice is here.\r
389     * We might want to use a hashtable instead of an array though.\r
390     */\r
391    TagType RegisterTag(unsigned char *tagname);\r
392 \r
393    bool EmptyText(DocID i) {\r
394        return Text->EmptyText(i);\r
395    }\r
396 \r
397    /** Prefix(s): search for texts prefixed by string s. */\r
398    TextCollection::document_result Prefix(uchar const *s) {\r
399       return Text->Prefix(s);\r
400    }\r
401 \r
402    /** Suffix(s): search for texts having string s as a suffix. */\r
403    TextCollection::document_result Suffix(uchar const *s) {\r
404       return Text->Suffix(s);\r
405    }\r
406 \r
407    /** Equal(s): search for texts equal to string s. */\r
408    TextCollection::document_result Equals(uchar const *s) {\r
409       return Text->Equal(s);\r
410    }\r
411 \r
412    /** Contains(s): search for texts containing string s.  */\r
413    TextCollection::document_result Contains(uchar const *s) {\r
414       return Text->Contains(s);\r
415    }\r
416 \r
417    /** LessThan(s): returns document identifiers for the texts that\r
418     * are lexicographically smaller than string s. */\r
419    TextCollection::document_result LessThan(uchar const *s) {\r
420       return Text->LessThan(s);\r
421    }\r
422    \r
423    /** IsPrefix(x): returns true if there is a text prefixed by string s. */\r
424    bool IsPrefix(uchar const *s) {\r
425       return Text->IsPrefix(s);\r
426    }          \r
427    \r
428    /** IsSuffix(s): returns true if there is a text having string s as a \r
429     * suffix.*/\r
430    bool IsSuffix(uchar const *s) {\r
431       return Text->IsSuffix(s);\r
432    }\r
433    \r
434    /** IsEqual(s): returns true if there is a text that equals given \r
435     * string s. */\r
436    bool IsEqual(uchar const *s) {\r
437       return Text->IsEqual(s);\r
438    }\r
439    \r
440    /** IsContains(s): returns true if there is a text containing string s. */\r
441    bool IsContains(uchar const *s) {\r
442       return Text->IsContains(s);\r
443    }\r
444    \r
445    /** IsLessThan(s): returns true if there is at least a text that is \r
446     * lexicographically smaller than string s. */\r
447    bool IsLessThan(uchar const *s) {\r
448       return Text->IsLessThan(s);\r
449    }\r
450    \r
451    /** Count(s): Global counting  */\r
452    unsigned Count(uchar const *s) {\r
453       return Text->Count(s);\r
454    }\r
455 \r
456    /** CountPrefix(s): counting version of Prefix(s). */\r
457    unsigned CountPrefix(uchar const *s) {\r
458       return Text->CountPrefix(s);\r
459    }\r
460    \r
461    /** CountSuffix(s): counting version of Suffix(s). */\r
462    unsigned CountSuffix(uchar const *s) {\r
463       return Text->CountSuffix(s);\r
464    }\r
465    \r
466    /** CountEqual(s): counting version of Equal(s). */\r
467    unsigned CountEqual(uchar const *s) {\r
468       return Text->CountEqual(s);\r
469    }\r
470    \r
471    /** CountContains(s): counting version of Contains(s). */\r
472    unsigned CountContains(uchar const *s) {\r
473       return Text->CountContains(s);\r
474    }\r
475    \r
476    /** CountLessThan(s): counting version of LessThan(s). */\r
477    unsigned CountLessThan(uchar const *s) {\r
478       return Text->CountLessThan(s);\r
479    }\r
480    \r
481    /** GetText(d): returns the text corresponding to document with\r
482     * id d. */\r
483    uchar* GetText(DocID d) {\r
484      \r
485        uchar * s = Text->GetText(d);\r
486        return (s[0] == 1 ? (s+1) : s);\r
487    }\r
488 \r
489    /** GetText(i, j): returns the texts corresponding to documents with\r
490     * ids i, i+1, ..., j. Texts are separated by '\0' character.  */\r
491    //   uchar* GetText(DocID i, DocID j) {\r
492    //  uchar * s = Text->GetText(i, j);\r
493    // return (s[0] == 1 ? (uchar*)"" : s);\r
494    //}\r
495 \r
496    TextCollection *getTextCollection() {\r
497       return Text;\r
498    }\r
499    \r
500    /** Save: saves XML tree data structure to file. */\r
501    void Save(int fd, char *filename);\r
502       \r
503    /** Load: loads XML tree data structure from file. sample_rate_text \r
504     * indicates the sample rate for the text search data structure. */\r
505    static XMLTree *Load(int fd, char *filename, bool load_tc, int sample_factor);   \r
506 \r
507    void insertTag(TagType tag, uint position);\r
508    \r
509    void print_stats();\r
510 \r
511    \r
512    /** Parenthesis functions */\r
513    treeNode Closing(treeNode x);\r
514 \r
515    bool IsOpen(treeNode x);\r
516 \r
517 \r
518    /** Print procedure */\r
519    void Print(int fd,treeNode x, bool no_text);\r
520    void Print(int fd,treeNode x) { Print(fd,x,false); }\r
521 \r
522   // The following are inlined here for speed\r
523   /** Tag(x): returns the tag identifier of node x. */\r
524 \r
525   TagType Tag(treeNode x) {\r
526     if (tags_blen == 8)\r
527       return  (TagType) (((uchar*)tags_fix)[(int) x]);\r
528     else\r
529       return (TagType) get_field(tags_fix,tags_blen, (int) x);\r
530   }\r
531 \r
532      /** FirstChild(x): returns the first child of node x, or NULLT if the node is a leaf\r
533     */\r
534    treeNode FirstChild(treeNode x) {\r
535            NULLT_IF(x==NULLT);\r
536            return fast_first_child(Par, x);\r
537    };\r
538 \r
539 \r
540    /** FirstElement(x): returns the first non text, non attribute child of node x, or NULLT\r
541     *    if none.\r
542     */\r
543    treeNode FirstElement(treeNode x){\r
544      {\r
545        NULLT_IF(x==NULLT);\r
546        x = fast_first_child(Par, x);\r
547        NULLT_IF(x == NULLT);\r
548        switch (Tag(x)){\r
549          \r
550        case PCDATA_TAG_ID:\r
551          x = x+2;\r
552          return (fast_inspect(Par,x)==OP)? x : NULLT;\r
553          \r
554        case ATTRIBUTE_TAG_ID:  \r
555          x = fast_next_sibling(Par,x);\r
556          if (x != NULLT && Tag(x) == PCDATA_TAG_ID){\r
557            x = x+2;\r
558            return (fast_inspect(Par,x)==OP)? x : NULLT;\r
559          } \r
560          else return x;     \r
561        default:\r
562          return x;\r
563        }\r
564      }\r
565    };\r
566 \r
567   /** NextSibling(x): returns the next sibling of node x, or NULLT if none \r
568    * exists. */\r
569   \r
570   treeNode NextSibling(treeNode x) {\r
571     NULLT_IF (x <= 0);\r
572     return fast_next_sibling(Par, x);\r
573   };\r
574   \r
575    /** NextElement(x): returns the first non text, non attribute sibling of node x, or NULLT\r
576     *    if none.\r
577     */\r
578   treeNode NextElement(treeNode x)\r
579   {\r
580     NULLT_IF(x <= 0);\r
581     x = fast_next_sibling(Par, x);\r
582     NULLT_IF(x == NULLT);   \r
583     if (Tag(x) == PCDATA_TAG_ID){\r
584       x = x+2;\r
585       return (fast_inspect(Par,x)==OP)? x : NULLT;\r
586     }\r
587     else return x;  \r
588   };\r
589      /** TaggedDesc(x,tag): returns the first node tagged tag with larger \r
590     * preorder than x and within the subtree of x. Returns NULT if there \r
591     * is none. */\r
592   treeNode TaggedDescendant(treeNode x, TagType tag)\r
593   {\r
594     \r
595           int s = (int) Tags->select_next(tag,node2tagpos(x));\r
596           NULLT_IF (s == -1);\r
597           \r
598           treeNode y = tagpos2node(s); // transforms the tag position into a node position\r
599           \r
600           return (fast_is_ancestor(Par,x,y) ? y : NULLT);\r
601   };\r
602   \r
603   treeNode TaggedFollowingBelow(treeNode x, TagType tag,treeNode ancestor)\r
604   {\r
605           treeNode close = fast_find_close(Par, x);\r
606           treeNode s = tagpos2node(Tags->select_next(tag, close));\r
607           \r
608           if (ancestor == Root() || s == NULLT || s < fast_find_close(Par,ancestor)) return s;\r
609           else return NULLT;\r
610   };\r
611     \r
612 };\r
613 \r
614 \r
615 \r
616 \r
617 #endif\r
618 \r