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