Added filename to Save() and Load()
[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 \r
99 \r
100 \r
101 \r
102 \r
103 class XMLTreeBuilder;\r
104 \r
105 class XMLTree {\r
106 \r
107   // Only the builder can access the constructor\r
108   friend class XMLTreeBuilder;\r
109 \r
110  private:\r
111    /** Balanced parentheses representation of the tree */\r
112    bp *Par;\r
113  \r
114    /** Mapping from tag identifer to tag name */  \r
115    std::vector<std::string> *TagName;\r
116    TagIdMap * tIdMap;\r
117   \r
118    /** Bit vector indicating with a 1 the positions of the non-empty texts. */\r
119    static_bitsequence *EBVector;  \r
120                       \r
121    /** Tag sequence represented with a data structure for rank and select */\r
122    static_sequence *Tags;\r
123    uint * tags_fix;\r
124    uint tags_blen, tags_len;\r
125 \r
126    /** The texts in the XML document */\r
127    TextCollection *Text;\r
128 \r
129    // Allows to disable the TextCollection for benchmarkin purposes\r
130    bool disable_tc;\r
131    \r
132    FILE* stream;\r
133    int   stream_fd; \r
134    std::string * buffer;\r
135    void myfputs(const char* s, FILE * fp){\r
136      buffer->append(s);\r
137      if (buffer->size() >= 100000){\r
138        fputs(buffer->c_str(),fp);\r
139        buffer->clear();\r
140      };\r
141 \r
142    }\r
143    void myfputc(const char c, FILE*fp){\r
144      buffer->append(1,c);\r
145      if (buffer->size() >= 100000){\r
146        fputs(buffer->c_str(),fp);\r
147        buffer->clear();\r
148      };\r
149    }\r
150    void mybufferflush(FILE* fp){\r
151      fputs(buffer->c_str(), fp);\r
152      buffer->clear();\r
153    }\r
154 \r
155    size_t myfprintf(const char* s, FILE * fp){\r
156      if (s == NULL)\r
157        return 0;\r
158      size_t i = buffer->size();\r
159      buffer->append(s);\r
160      size_t j = buffer->size();\r
161      if (buffer->size() >= 100000){\r
162        fputs(buffer->c_str(),fp);\r
163        buffer->clear();\r
164      };\r
165      return (j-i);\r
166    }\r
167 \r
168    void PrintNode(treeNode n, int fd);\r
169    /** Data structure constructors */\r
170    XMLTree(){ buffer = 0;};\r
171 \r
172    // non const pointer are freed by this method.\r
173    XMLTree( pb * const par, uint npar,  std::vector<std::string> * const TN,  TagIdMap * const tim, uint *empty_texts_bmp, TagType *tags,\r
174            TextCollection * const TC, bool dis_tc);\r
175 \r
176 public: \r
177    /** Data structure destructor */\r
178    ~XMLTree();\r
179    \r
180    /** root(): returns the tree root. */\r
181    treeNode Root() { return 0; }\r
182 \r
183    /** Size() :  Number of parenthesis */\r
184    unsigned int Size(){\r
185      return tags_len/2;\r
186    }\r
187 \r
188    /** SubtreeSize(x): the number of nodes (and attributes) in the subtree of \r
189     * node x. */\r
190    int SubtreeSize(treeNode x);\r
191   \r
192    /** SubtreeTags(x,tag): the number of occurrences of tag within the subtree \r
193     * of node x. */\r
194    int SubtreeTags(treeNode x, TagType tag);\r
195    \r
196    /** SubtreeElements(x) of element nodes in the subtree of x\r
197     */\r
198    int SubtreeElements(treeNode x);\r
199 \r
200    /** IsLeaf(x): returns whether node x is leaf or not. In the succinct \r
201     * representation this is just a bit inspection. */\r
202 \r
203    bool IsLeaf(treeNode x);\r
204 \r
205    /** IsAncestor(x,y): returns whether node x is ancestor of node y. */\r
206 \r
207    bool IsAncestor(treeNode x, treeNode y);\r
208   \r
209    /** IsChild(x,y): returns whether node x is parent of node y. */\r
210    bool IsChild(treeNode x, treeNode y);\r
211 \r
212    /** IsFirstChild(x): returns whether node x is the first child of its parent. */\r
213    /* OCAML */\r
214    bool IsFirstChild(treeNode x);\r
215      \r
216    /** NumChildren(x): number of children of node x. Constant time with the \r
217     * data structure of Sadakane. */\r
218    int NumChildren(treeNode x);\r
219 \r
220    /** ChildNumber(x): returns i if node x is the i-th children of its \r
221     * parent. */\r
222    int ChildNumber(treeNode x);\r
223 \r
224    /** Depth(x): depth of node x, a simple binary rank on the parentheses \r
225     * sequence. */\r
226    int Depth(treeNode x);\r
227    \r
228    /** Preorder(x): returns the preorder number of node x, just regarding tree \r
229     * nodes (and not texts). */ \r
230    int Preorder(treeNode x);\r
231    \r
232    /** Postorder(x): returns the postorder number of node x, just regarding \r
233     * tree nodes (and not texts). */\r
234    int Postorder(treeNode x);\r
235       \r
236    /** Tag(x): returns the tag identifier of node x. */\r
237    TagType Tag(treeNode x) {\r
238      if (tags_blen == 8)\r
239        return  (TagType) (((uchar*)tags_fix)[(int) x]);\r
240      else\r
241        return (TagType) get_field(tags_fix,tags_blen, (int) x);\r
242    }\r
243 \r
244    /** DocIds(x): returns the range (i.e., a pair of integers) of document \r
245     * identifiers that descend from node x. */\r
246    range DocIds(treeNode x);\r
247 \r
248    /** Parent(x): returns the parent node of node x. */\r
249    treeNode Parent(treeNode x);\r
250    /* Assumes x is neither 0 nor -1 */\r
251    \r
252    /** Child(x,i): returns the i-th child of node x, assuming it exists. */   \r
253    treeNode Child(treeNode x, int i);\r
254 \r
255    /** FirstChild(x): returns the first child of node x, or NULLT if the node is a leaf\r
256     */\r
257    treeNode FirstChild(treeNode x);\r
258 \r
259    /** FirstElement(x): returns the first non text, non attribute child of node x, or NULLT\r
260     *    if none.\r
261     */\r
262    treeNode FirstElement(treeNode x);\r
263 \r
264    /** LastChild(x): returns the last child of node x.  */\r
265    treeNode LastChild(treeNode x);\r
266    \r
267    /** NextSibling(x): returns the next sibling of node x, or NULLT if none \r
268     * exists. */\r
269 \r
270    treeNode NextSibling(treeNode x);\r
271 \r
272    /** NextElement(x): returns the first non text, non attribute sibling of node x, or NULLT\r
273     *    if none.\r
274     */\r
275    treeNode NextElement(treeNode x);\r
276 \r
277    /** PrevSibling(x): returns the previous sibling of node x, assuming it \r
278     * exists. */\r
279 \r
280    treeNode PrevSibling(treeNode x);\r
281    \r
282    /** TaggedChild(x,tag): returns the first child of node x tagged tag, or \r
283     * NULLT if there is none. Because of the balanced-parentheses representation \r
284     * of the tree, this operation is not supported efficiently, just iterating \r
285     * among the children of node x until finding the desired child. */\r
286    treeNode TaggedChild(treeNode x, TagType tag);\r
287    \r
288    treeNode SelectChild(treeNode x, TagIdSet * tags);\r
289 \r
290    /** TaggedFollowingSibling(x,tag): returns the first sibling of node x tagged tag, or \r
291     *  NULLT if there is none. */\r
292    treeNode TaggedFollowingSibling(treeNode x, TagType tag);\r
293    \r
294    treeNode SelectFollowingSibling(treeNode x, TagIdSet * tags);\r
295 \r
296    /** TaggedDesc(x,tag): returns the first node tagged tag with larger \r
297     * preorder than x and within the subtree of x. Returns NULT if there \r
298     * is none. */\r
299    treeNode TaggedDescendant(treeNode x, TagType tag);\r
300 \r
301    treeNode SelectDescendant(treeNode x, TagIdSet * tags);\r
302 \r
303    /** TaggedPrec(x,tag): returns the first node tagged tag with smaller \r
304     * preorder than x and not an ancestor of x. Returns NULLT if there \r
305     * is none. */\r
306    treeNode TaggedPreceding(treeNode x, TagType tag);\r
307   \r
308    /** TaggedFoll(x,tag): returns the first node tagged tag with larger \r
309     * preorder than x and not in the subtree of x. Returns NULLT if there \r
310     * is none. */\r
311    treeNode TaggedFollowing(treeNode x, TagType tag);\r
312 \r
313    treeNode TaggedFollowingBelow(treeNode x, TagType tag,treeNode ancestor);     \r
314 \r
315    treeNode SelectFollowingBelow(treeNode x, TagIdSet * tags, treeNode ancestor);\r
316 \r
317    treeNode TaggedFollowingBefore(treeNode x, TagType tag,treeNode closing);\r
318 \r
319    treeNode SelectFollowingBefore(treeNode x, TagIdSet * tags, treeNode closing);\r
320 \r
321    /** TaggedAncestor(x, tag): returns the closest ancestor of x tagged \r
322      * tag. Return NULLT is there is none. */\r
323    treeNode TaggedAncestor(treeNode x, TagType tag);\r
324  \r
325    /** PrevText(x): returns the document identifier of the text to the left of \r
326     * node x, or NULLT if x is the root node. */\r
327    DocID PrevText(treeNode x);\r
328    \r
329    /** NextText(x): returns the document identifier of the text to the right of \r
330     * node x, or NULLT if x is the root node. */\r
331    DocID NextText(treeNode x);\r
332    \r
333    /** MyText(x): returns the document identifier of the text below node x, or \r
334     * NULLT if x is not a leaf node. */\r
335    DocID MyText(treeNode x);\r
336    DocID MyTextUnsafe(treeNode x);\r
337 \r
338    /** TextXMLId(d): returns the preorder of document with identifier d in the \r
339     * tree consisting of all tree nodes and all text nodes. */\r
340    int TextXMLId(DocID d);\r
341    \r
342    /** NodeXMLId(x): returns the preorder of node x in the tree consisting of \r
343     * all tree nodes and all text nodes. */\r
344    int NodeXMLId(treeNode x);\r
345    \r
346    /** ParentNode(d): returns the parent node of document identifier d. */\r
347    treeNode ParentNode(DocID d);\r
348    \r
349    treeNode PrevNode(DocID d);\r
350 \r
351    /** GetTagId(tagname): returns the tag identifier corresponding to a given \r
352     * tag name. Returns NULLT in case that the tag name does not exists. */\r
353    TagType GetTagId(unsigned char *tagname);\r
354 \r
355    /** GetTagName(tagid): returns the tag name of a given tag identifier. \r
356     * Returns NULL in case that the tag identifier is not valid.*/\r
357    unsigned char *GetTagName(TagType tagid);\r
358 \r
359    /** GetTagName(tagid): returns the tag name of a given tag identifier.     \r
360     *  The result is just a reference and should not be freed by the caller.\r
361     */\r
362    const unsigned char *GetTagNameByRef(TagType tagid);\r
363 \r
364    /** RegisterTag adds a new tag to the tag collection this is needed\r
365     * if the query contains a tag which is not in the document, we need\r
366     * to give this new tag a fresh id and store it somewhere. A logical\r
367     * choice is here.\r
368     * We might want to use a hashtable instead of an array though.\r
369     */\r
370    TagType RegisterTag(unsigned char *tagname);\r
371 \r
372    bool EmptyText(DocID i) {\r
373        return Text->EmptyText(i);\r
374    }\r
375 \r
376    /** Prefix(s): search for texts prefixed by string s. */\r
377    TextCollection::document_result Prefix(uchar const *s) {\r
378       return Text->Prefix(s);\r
379    }\r
380 \r
381    /** Suffix(s): search for texts having string s as a suffix. */\r
382    TextCollection::document_result Suffix(uchar const *s) {\r
383       return Text->Suffix(s);\r
384    }\r
385 \r
386    /** Equal(s): search for texts equal to string s. */\r
387    TextCollection::document_result Equals(uchar const *s) {\r
388       return Text->Equal(s);\r
389    }\r
390 \r
391    /** Contains(s): search for texts containing string s.  */\r
392    TextCollection::document_result Contains(uchar const *s) {\r
393       return Text->Contains(s);\r
394    }\r
395 \r
396    /** LessThan(s): returns document identifiers for the texts that\r
397     * are lexicographically smaller than string s. */\r
398    TextCollection::document_result LessThan(uchar const *s) {\r
399       return Text->LessThan(s);\r
400    }\r
401    \r
402    /** IsPrefix(x): returns true if there is a text prefixed by string s. */\r
403    bool IsPrefix(uchar const *s) {\r
404       return Text->IsPrefix(s);\r
405    }          \r
406    \r
407    /** IsSuffix(s): returns true if there is a text having string s as a \r
408     * suffix.*/\r
409    bool IsSuffix(uchar const *s) {\r
410       return Text->IsSuffix(s);\r
411    }\r
412    \r
413    /** IsEqual(s): returns true if there is a text that equals given \r
414     * string s. */\r
415    bool IsEqual(uchar const *s) {\r
416       return Text->IsEqual(s);\r
417    }\r
418    \r
419    /** IsContains(s): returns true if there is a text containing string s. */\r
420    bool IsContains(uchar const *s) {\r
421       return Text->IsContains(s);\r
422    }\r
423    \r
424    /** IsLessThan(s): returns true if there is at least a text that is \r
425     * lexicographically smaller than string s. */\r
426    bool IsLessThan(uchar const *s) {\r
427       return Text->IsLessThan(s);\r
428    }\r
429    \r
430    /** Count(s): Global counting  */\r
431    unsigned Count(uchar const *s) {\r
432       return Text->Count(s);\r
433    }\r
434 \r
435    /** CountPrefix(s): counting version of Prefix(s). */\r
436    unsigned CountPrefix(uchar const *s) {\r
437       return Text->CountPrefix(s);\r
438    }\r
439    \r
440    /** CountSuffix(s): counting version of Suffix(s). */\r
441    unsigned CountSuffix(uchar const *s) {\r
442       return Text->CountSuffix(s);\r
443    }\r
444    \r
445    /** CountEqual(s): counting version of Equal(s). */\r
446    unsigned CountEqual(uchar const *s) {\r
447       return Text->CountEqual(s);\r
448    }\r
449    \r
450    /** CountContains(s): counting version of Contains(s). */\r
451    unsigned CountContains(uchar const *s) {\r
452       return Text->CountContains(s);\r
453    }\r
454    \r
455    /** CountLessThan(s): counting version of LessThan(s). */\r
456    unsigned CountLessThan(uchar const *s) {\r
457       return Text->CountLessThan(s);\r
458    }\r
459    \r
460    /** GetText(d): returns the text corresponding to document with\r
461     * id d. */\r
462    uchar* GetText(DocID d) {\r
463      \r
464        uchar * s = Text->GetText(d);\r
465        return (s[0] == 1 ? (s+1) : s);\r
466    }\r
467 \r
468    /** GetText(i, j): returns the texts corresponding to documents with\r
469     * ids i, i+1, ..., j. Texts are separated by '\0' character.  */\r
470    //   uchar* GetText(DocID i, DocID j) {\r
471    //  uchar * s = Text->GetText(i, j);\r
472    // return (s[0] == 1 ? (uchar*)"" : s);\r
473    //}\r
474 \r
475    TextCollection *getTextCollection() {\r
476       return Text;\r
477    }\r
478    \r
479    /** Save: saves XML tree data structure to file. */\r
480    void Save(int fd, char *filename);\r
481       \r
482    /** Load: loads XML tree data structure from file. sample_rate_text \r
483     * indicates the sample rate for the text search data structure. */\r
484    static XMLTree *Load(int fd, char *filename, bool load_tc, int sample_factor);   \r
485 \r
486    void insertTag(TagType tag, uint position);\r
487    \r
488    void print_stats();\r
489 \r
490    \r
491    /** Parenthesis functions */\r
492    treeNode Closing(treeNode x);\r
493 \r
494    bool IsOpen(treeNode x);\r
495 \r
496 \r
497    /** Print procedure */\r
498    void Print(int fd,treeNode x, bool no_text);\r
499    void Print(int fd,treeNode x) { Print(fd,x,false); }\r
500 \r
501 };\r
502 \r
503 \r
504 \r
505 \r
506 #endif\r
507 \r