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