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