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