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