Fixes bug where the tag ID used for the root is xml_tree::CLOSE_TAG.
[SXSI/XMLTree.git] / xml-tree.cpp
1 extern "C" {
2 #include <unistd.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 }
7
8 #include <stdexcept>
9 #include <cerrno>
10 #include <cstring>
11 #include <cstdio>
12 #include "xml-tree.hpp"
13
14 using namespace SXSI;
15
16 const xml_tree::node_t xml_tree::NIL;
17 const xml_tree::node_t xml_tree::ROOT;
18
19
20 const xml_tree::tag_t xml_tree::NIL_TAG_ID;
21 const char* xml_tree::NIL_TAG = "<!NIL!>";
22 const xml_tree::tag_t xml_tree::DOCUMENT_OPEN_TAG_ID;
23 const char* xml_tree::DOCUMENT_OPEN_TAG = "";
24 const xml_tree::tag_t xml_tree::ATTRIBUTE_OPEN_TAG_ID;
25 const char* xml_tree::ATTRIBUTE_OPEN_TAG = "<@>";
26 const xml_tree::tag_t xml_tree::PCDATA_OPEN_TAG_ID;
27 const char* xml_tree::PCDATA_OPEN_TAG = "<$>";
28 const xml_tree::tag_t xml_tree::ATTRIBUTE_DATA_OPEN_TAG_ID;
29 const char* xml_tree::ATTRIBUTE_DATA_OPEN_TAG = "<@$>";
30 const xml_tree::tag_t xml_tree::CLOSE_TAG_ID;
31 const char* xml_tree::CLOSE_TAG = "</>";
32
33
34 static int bits8 (int t ) {
35   int r = bits(t);
36   if (r <= 8)
37     return 8;
38   else if (r <= 16)
39     return 16;
40   else
41     return r;
42 }
43
44
45 static bool array_mem(xml_tree::tag_t *a, xml_tree::tag_t t)
46 {
47   for(; *a != xml_tree::NIL_TAG_ID; a++){
48     if (*a >= t) return (*a == t);
49   };
50   return false;
51 }
52
53 static void ufread(void *ptr, size_t size, size_t nmemb, FILE *stream)
54  {
55     size_t res;
56     res = fread(ptr,size,nmemb,stream);
57     if (res < nmemb)
58       throw std::runtime_error("ufread I/O error" );
59     return;
60  }
61
62 static void ufwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
63  {
64     size_t res;
65     res = fwrite(ptr,size,nmemb,stream);
66     if (res < nmemb)
67       throw std::runtime_error("ufwrite I/O error");
68     return;
69  }
70
71
72
73 xml_tree::xml_tree()
74 {
75   print_stack = 0;
76   print_buffer = 0;
77 }
78
79 xml_tree::xml_tree(std::vector<int32_t> *tags_,
80                    std::unordered_map<std::string, int32_t> *tag_ids,
81                    bit_vector *parbitmap,
82                    bool disable_tc,
83                    SXSI::TextCollectionBuilder *tc_builder,
84                    SXSI::TextCollectionBuilder::index_type_t idx_type,
85                    bit_vector *textbitmap)
86 {
87   print_stack = 0;
88   print_buffer = 0;
89
90   size_t npar = parbitmap->size();
91   parbitmap->pack();
92   par = bp_construct(npar,
93                      parbitmap->get_vector_ptr(),
94                      OPT_DEGREE);
95   delete parbitmap;
96
97   this->tag_ids = tag_ids;
98   tag_names = new std::vector<std::string>();
99   tag_names->resize(tag_ids->size());
100   for(auto val : *(this->tag_ids))
101     (*this->tag_names)[val.second] = val.first;
102
103   uint32_t max_tag = tag_names->size() - 1;
104
105   bit_vector *tmp_bitmap = new bit_vector(npar, 1, 0);
106   uint32_t * buff = tmp_bitmap->get_vector_ptr();
107   for(int32_t i = 0; i <= max_tag; i++){
108     uint32_t ones = 0;
109     for (size_t k = 0; k < npar; k++){
110       bool t = (i == (*tags_)[k]);
111       tmp_bitmap->set(k, t);
112       ones += t;
113     };
114
115     this->tags.push_back(new static_bitsequence_sdarray(buff, npar, ones));
116   }
117   delete tmp_bitmap;
118   delete [] buff;
119
120   //static_bitsequence_builder *bmb = new static_bitsequence_builder_sdarray();
121   //alphabet_mapper *am = new alphabet_mapper_none();
122
123 //  this->tags = new static_sequence_bs((uint32_t*)&((*tags)[0]), npar, am, bmb);
124
125   bits_per_tag = bits8(max_tag);
126   tag_seq_len = npar;
127   tag_seq = new uint32_t[uint_len(bits_per_tag, tag_seq_len)];
128   for(size_t i = 0; i < (size_t) tag_seq_len; i++)
129     set_field(tag_seq, bits_per_tag, i, (uint32_t) (*tags_)[i]);
130
131   delete tags_;
132
133   if (disable_tc) {
134     text_positions = 0;
135     text_collection = 0;
136   } else {
137     textbitmap->pack();
138     uint32_t * textbm = textbitmap->get_vector_ptr();
139     text_positions = new static_bitsequence_rrr02(textbm,
140                                                   npar,
141                                                   32);
142     //delete [] textbm;
143     //delete textbitmap;
144
145     this->text_index_type = idx_type;
146     text_collection = tc_builder->InitTextCollection();
147     delete tc_builder;
148   };
149
150 }
151
152 xml_tree::~xml_tree()
153 {
154   bp_delete(par);
155
156   for(int i = 0; i < tag_names->size(); i++){
157     delete tags[i];
158     tags[i] = 0;
159   };
160
161
162   delete [] tag_seq;
163   delete tag_names;
164   delete tag_ids;
165   if (text_collection) delete text_collection;
166   if (text_positions) delete text_positions;
167 }
168
169 bool xml_tree::is_child(xml_tree::node_t x, xml_tree::node_t y) const
170 {
171   return !is_leaf(x) && is_ancestor(y, x) && depth(x)+1 == depth(y);
172 }
173
174 uint32_t xml_tree::depth(xml_tree::node_t x) const
175 {
176   return bp_depth(this->par, x);
177 }
178
179
180 uint32_t xml_tree::preorder(xml_tree::node_t x) const
181 {
182   return bp_preorder_rank(this->par, x);
183 }
184
185 uint32_t xml_tree::postorder(xml_tree::node_t x) const
186 {
187   return bp_postorder_rank(this->par, x);
188 }
189
190 xml_tree::node_t
191 xml_tree::select_child(xml_tree::node_t x, xml_tree::tag_t *tags) const
192 {
193   if (is_nil(x) || is_leaf(x)) return xml_tree::NIL;
194   xml_tree::node_t child = first_child(x);
195   if (array_mem(tags, tag(child))) return child;
196   return select_sibling(child, tags);
197 }
198
199
200 xml_tree::node_t
201 xml_tree::select_sibling(xml_tree::node_t x, xml_tree::tag_t *tags) const
202 {
203   xml_tree::node_t sibling = next_sibling(x);
204   xml_tree::tag_t t;
205   while(!is_nil(sibling)) {
206     t = tag(sibling);
207     if (array_mem(tags, t)) return sibling;
208     sibling = next_sibling(sibling);
209   };
210   return sibling;
211 }
212
213
214 void xml_tree::save(int fd, char* s)
215 {
216   FILE* fp;
217   int fd2 = dup(fd);
218
219   fp = fdopen(fd2, "w");
220
221   if (fd == 0) throw(std::runtime_error(strerror(errno)));
222   saveTree(par, fp); //TODO use new api
223
224   int ntags = tag_names->size();
225
226   ufwrite(&ntags, sizeof(int), 1, fp);
227   for (int i = 0; i < ntags;i++)
228     fprintf(fp, "%s\n", tag_names->at(i).c_str());
229
230   //tags->save(fp);
231   for(int i = 0; i < ntags; i++)
232     tags[i]->save(fp);
233
234   ufwrite(&bits_per_tag, sizeof(uint),1,fp);
235   ufwrite(&tag_seq_len, sizeof(uint),1,fp);
236   ufwrite(tag_seq, sizeof(uint), uint_len(bits_per_tag, tag_seq_len), fp);
237
238   bool disable_tc = text_collection == 0 || text_positions == 0;
239
240   ufwrite(&disable_tc, sizeof(bool),1,fp);
241
242   if (!disable_tc) {
243     text_positions->save(fp);
244     ufwrite(&text_index_type,
245             sizeof(TextCollectionBuilder::index_type_t),
246             1, fp);
247
248     std::string file(s);
249     switch (text_index_type){
250     case TextCollectionBuilder::index_type_default:
251       file.append("_default");
252       break;
253     case TextCollectionBuilder::index_type_swcsa:
254       file.append("_swcsa");
255       break;
256     case TextCollectionBuilder::index_type_rlcsa:
257       file.append("_rlcsa");
258       break;
259     };
260
261     text_collection->Save(fp, file.c_str());
262   };
263
264   fflush(fp);
265   fclose(fp);
266
267 }
268
269 xml_tree* xml_tree::load(int fd, char* name, bool load_tc, int sf)
270 {
271   FILE *fp;
272   char buffer[1024];
273
274   int i;
275   buffer[1023] = '\0';
276   fp = fdopen(fd, "r");
277   xml_tree *tree = new xml_tree();
278
279   tree->par = loadTree(fp); //TODO use new api
280   tree->tag_names = new std::vector<std::string>();
281   tree->tag_ids = new std::unordered_map<std::string, xml_tree::tag_t>();
282   std::string s;
283   int ntags;
284
285   ufread(&ntags, sizeof(int), 1, fp);
286
287   for (i = 0; i < ntags; i++) {
288     if (fgets(buffer, 1022, fp) != buffer)
289       throw std::runtime_error("xml_tree::load: cannot read tag list");
290     s = buffer;
291     // remove the trailing \n
292     s.erase(s.size()-1);
293     tree->tag_names->push_back(s);
294     tree->tag_ids->insert(std::make_pair(s,
295                                          static_cast<xml_tree::tag_t>(i)));
296
297   };
298
299   for(int i = 0; i < ntags; i++){
300     tree->tags.push_back(static_bitsequence_sdarray::load(fp));
301   };
302
303   //tree->tags = static_sequence_bs::load(fp);
304   ufread(&tree->bits_per_tag, sizeof(uint), 1, fp);
305   fprintf(stderr, "\nBits per tag: %u\n", tree->bits_per_tag);
306   ufread(&tree->tag_seq_len, sizeof(uint), 1, fp);
307   size_t size = uint_len(tree->bits_per_tag, tree->tag_seq_len);
308   tree->tag_seq = new uint[size];
309   ufread(tree->tag_seq, sizeof(uint), size, fp);
310
311   bool disable_tc;
312   ufread(&disable_tc, sizeof(bool), 1, fp);
313
314   if (disable_tc || !load_tc) {
315     tree->text_positions = 0;
316     tree->text_collection = 0;
317   } else {
318
319     tree->text_positions = static_bitsequence_rrr02::load(fp);
320
321     ufread(&tree->text_index_type,
322            sizeof(TextCollectionBuilder::index_type_t), 1, fp);
323
324     std::string file(name);
325     switch (tree->text_index_type){
326     case TextCollectionBuilder::index_type_default:
327       file.append("_default");
328       break;
329     case TextCollectionBuilder::index_type_swcsa:
330       file.append("_swcsa");
331       break;
332     case TextCollectionBuilder::index_type_rlcsa:
333       file.append("_rlcsa");
334       break;
335     };
336
337
338     tree->text_collection =
339       TextCollection::Load(fp,
340                            file.c_str(),
341                            TextCollection::index_mode_default,
342                            sf);
343
344   };
345   return tree;
346 }
347
348
349
350 uint32_t xml_tree::num_children(xml_tree::node_t x) const
351 {
352   return bp_degree(par, x);
353 }
354
355 uint32_t xml_tree::child_pos(xml_tree::node_t x) const
356 {
357   return bp_child_rank(par, x);
358 }
359
360 xml_tree::node_t xml_tree::child(xml_tree::node_t x, uint32_t i) const
361 {
362   if (i < 10) return bp_naive_child(par, x, i);
363   else bp_child(par, x, i);
364 }
365
366 std::pair<int32_t, int32_t> xml_tree::text_id_range(xml_tree::node_t x) const
367 {
368   int32_t i, j;
369   i = text_positions->rank1(x) - 1;
370   j = text_positions->rank1(x + 2 * bp_subtree_size(par, x) - 2);
371   if (i == j)
372     return std::make_pair(xml_tree::NIL, xml_tree::NIL);
373   else
374     return std::make_pair(i + 1, j);
375 }
376
377 int32_t xml_tree::text_id(xml_tree::node_t x) const
378 {
379   return (int32_t) text_positions->rank1(x) - 1;
380 }
381
382 unsigned char* xml_tree::get_text(int32_t id) const
383 {
384   unsigned char * s = text_collection->GetText(id);
385   return s + (s[0] == 1);
386 }
387
388 void xml_tree::uflush(int fd)
389 {
390   size_t size = print_buffer->size();
391   if (size < BUFFER_SIZE) return;
392   uflush_r(fd, size);
393 }
394
395 void xml_tree::flush(int fd)
396 {
397   uflush_r(fd, print_buffer->size());
398 }
399
400
401 void xml_tree::uflush_r(int fd, size_t s)
402 {
403   if (s == 0 || print_buffer == 0 || fd <= 0) return;
404   size_t written;
405   while (1) {
406     written = write(fd, print_buffer->data(), s);
407     if ((written < 0) && (errno == EAGAIN || errno == EINTR)){
408       continue;
409     };
410     break;
411   };
412   print_buffer->clear();
413 }
414
415 void xml_tree::uput_str(std::string s, int fd)
416 {
417   print_buffer->append(s);
418   uflush(fd);
419 }
420 void xml_tree::uputs(const char* s, int fd)
421 {
422   print_buffer->append(s);
423   uflush(fd);
424 }
425 void xml_tree::uputc(const char c, int fd)
426 {
427   print_buffer->push_back(c);
428   uflush(fd);
429 }
430
431 const char * xml_tree::get_tag_name_by_ref(xml_tree::tag_t tagid) const
432 {
433
434    unsigned char *s;
435    if (tagid < 0 || tagid >= tag_names->size())
436      return "<INVALID TAG>";
437
438    return (const char *) (*tag_names)[tagid].c_str();
439 }
440
441 xml_tree::tag_t xml_tree::register_tag(char *s)
442 {
443   auto found = tag_ids->find(std::string(s));
444   if (found == tag_ids->end())
445     return xml_tree::NIL_TAG_ID;
446   else
447     return (*found).second;
448 }
449
450 size_t xml_tree::uprintf(const char*s, int fd)
451 {
452      if (s == 0) return 0;
453      size_t i;
454      char c;
455      for (i = 0; (c = s[i]); i++) {
456        switch (c) {
457        case '"':
458          uputs("&quot;", fd);
459          break;
460        case '&':
461          uputs("&amp;", fd);
462          break;
463        case '\'':
464          uputs("&apos;", fd);
465          break;
466        case '<':
467          uputs("&lt;", fd);
468          break;
469        case '>':
470          uputs("&gt;", fd);
471          break;
472        default:
473          uputc(c, fd);
474
475        };
476      };
477      return i;
478 }
479
480 void xml_tree::print(xml_tree::node_t x, int fd, bool no_text)
481 {
482
483   if (print_buffer == 0) {
484     print_buffer = new std::string(BUFFER_SIZE, 0);
485     print_buffer->clear();
486     print_stack = new std::vector<std::string>();
487     print_stack->reserve(256);
488   };
489
490   xml_tree::node_t fin = bp_find_close(par, x);
491   xml_tree::node_t n = x;
492   xml_tree::tag_t label = tag(n);
493   unsigned char * orig_text;
494   unsigned char * current_text;
495
496   auto r = text_id_range(x);
497   if (r.first == xml_tree::NIL)
498     current_text = 0;
499   else
500     current_text = text_collection->GetText(r.first, r.second);
501   current_text += (current_text[0] == 1);
502
503   orig_text = current_text;
504
505   size_t read = 0;
506
507   while (n <= fin) {
508
509     if (bp_inspect(par, n)) {
510       if (label == xml_tree::PCDATA_OPEN_TAG_ID){
511         if (no_text) {
512           uputs("<$/>", fd);
513         } else {
514           read = uprintf( (const char*) current_text, fd);
515           current_text += read + 1;
516         };
517         n += 2; // skip closin $
518         label = tag(n);
519       } else {
520
521         uputc('<', fd);
522         uput_str((*tag_names)[label], fd);
523         n++;
524         if (bp_inspect(par, n)) {
525           print_stack->push_back((*tag_names)[label]);
526           label = tag(n);
527           if (label == xml_tree::ATTRIBUTE_OPEN_TAG_ID) {
528             n++;
529             if (no_text) uputs("><@@>", fd);
530
531             while (bp_inspect(par, n))
532               if (no_text) {
533                 uputc('<', fd);
534                 uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
535                 uputc('>', fd);
536                 uputs("<$@/></", fd);
537                 uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
538                 uputc('>', fd);
539                 n += 4;
540               } else {
541                 uputc(' ', fd);
542                 uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
543                 n++;
544                 uputs("=\"", fd);
545                 read = uprintf((const char*) current_text, fd);
546                 current_text += read + 1;
547                 uputc('"', fd);
548                 n += 3;
549               };
550
551             if (no_text)
552               uputs("</@@>", fd);
553             else uputc('>', fd);
554             n++;
555             label = tag(n);
556           } else
557             uputc('>', fd);
558         } else {
559           uputs("/>", fd);
560           n++;
561           label = tag(n);
562         };
563       };
564     } else do {
565       uputs("</", fd);
566       uput_str(print_stack->back(), fd);
567       uputc('>', fd);
568       print_stack->pop_back();
569       n++;
570       } while (!bp_inspect(par, n) && !print_stack->empty());
571     label = tag(n);
572   };
573   uputc('\n', fd);
574   if (orig_text && text_index_type != TextCollectionBuilder::index_type_default)
575     if (*orig_text == '\0')
576       text_collection->DeleteText(orig_text - 1);
577     else
578       text_collection->DeleteText(orig_text);
579
580 }
581
582 // void xml_tree::print(xml_tree::node_t x, int fd, bool no_text)
583 // {
584 //   if (print_buffer == 0) {
585 //     print_buffer = new std::string(BUFFER_SIZE, 0);
586 //     print_buffer->clear();
587 //     print_stack = new std::vector<std::string>();
588 //     print_stack->reserve(256);
589 //   };
590
591 //   xml_tree::node_t fin = bp_find_close(par, x);
592 //   xml_tree::node_t n = x;
593 //   xml_tree::tag_t label = tag(n);
594 //   unsigned char * current_text;
595
596
597 //   while (n <= fin) {
598
599 //     if (bp_inspect(par, n)) {
600 //       if (label == xml_tree::PCDATA_OPEN_TAG_ID){
601 //         if (no_text) {
602 //           uputs("<$/>", fd);
603 //         } else {
604 //        current_text = get_text(text_id(n));
605 //        uprintf( (const char*) (current_text + (current_text[0] == 1)), fd);
606
607 //        if (current_text && text_index_type != TextCollectionBuilder::index_type_default)
608 //          text_collection->DeleteText(current_text);
609
610 //        n += 2; // skip closin $
611 //        label = tag(n);
612 //      };
613 //       } else {
614 //        uputc('<', fd);
615 //        uput_str((*tag_names)[label], fd);
616 //        n++;
617 //        if (bp_inspect(par, n)) {
618 //          print_stack->push_back((*tag_names)[label]);
619 //          label = tag(n);
620 //          if (label == xml_tree::ATTRIBUTE_OPEN_TAG_ID) {
621 //            n++;
622 //            if (no_text) uputs("><@@>", fd);
623               
624 //            while (bp_inspect(par, n))
625 //              if (no_text) {
626 //                uputc('<', fd);
627 //                uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
628 //                uputc('>', fd);
629 //                uputs("<$@/></", fd);
630 //                uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
631 //                uputc('>', fd);
632 //                n += 4;
633 //              } else {
634 //                uputc(' ', fd);
635 //                uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
636 //                n+= 2;
637 //                uputs("=\"", fd);
638 //                current_text = get_text(text_id(n));
639 //                uprintf((const char*) (current_text + (current_text[0] == 1)), fd);
640 //                if (current_text && text_index_type != TextCollectionBuilder::index_type_default)
641 //                    text_collection->DeleteText(current_text);
642 //                uputc('"', fd);
643 //                n += 2;
644 //              };
645
646 //            if (no_text)
647 //              uputs("</@@>", fd);
648 //            else uputc('>', fd);
649 //            n++;
650 //            label = tag(n);
651 //          } else
652 //            uputc('>', fd);
653 //        } else {
654 //          uputs("/>", fd);
655 //          n++;
656 //          label = tag(n);
657 //        };
658 //      };
659 //       } else do {
660 //        uputs("</", fd);
661 //        uput_str(print_stack->back(), fd);
662 //        uputc('>', fd);
663 //        print_stack->pop_back();
664 //        n++;
665 //      } while (!bp_inspect(par, n) && !print_stack->empty());
666 //       label = tag(n);
667 //     };
668 //   uputc('\n', fd);
669
670 // }