Various fixes, mainly tagged_sibling/select_sibling.
[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
46
47 static void ufread(void *ptr, size_t size, size_t nmemb, FILE *stream)
48  {
49     size_t res;
50     res = fread(ptr,size,nmemb,stream);
51     if (res < nmemb)
52       throw std::runtime_error("ufread I/O error" );
53     return;
54  }
55
56 static void ufwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
57  {
58     size_t res;
59     res = fwrite(ptr,size,nmemb,stream);
60     if (res < nmemb)
61       throw std::runtime_error("ufwrite I/O error");
62     return;
63  }
64
65
66
67 xml_tree::xml_tree()
68 {
69   print_stack = 0;
70   print_buffer = 0;
71 }
72
73 xml_tree::xml_tree(std::vector<int32_t> *tags,
74                    std::unordered_map<std::string, int32_t> *tag_ids,
75                    bit_vector *parbitmap,
76                    bool disable_tc,
77                    SXSI::TextCollectionBuilder *tc_builder,
78                    SXSI::TextCollectionBuilder::index_type_t idx_type,
79                    bit_vector *textbitmap)
80 {
81   print_stack = 0;
82   print_buffer = 0;
83
84   size_t npar = parbitmap->size();
85   parbitmap->pack();
86
87   par = bp_construct(npar,
88                      parbitmap->get_vector_ptr(),
89                      OPT_DEGREE);
90   delete parbitmap;
91
92   this->tag_ids = tag_ids;
93   tag_names = new std::vector<std::string>();
94   tag_names->resize(tag_ids->size());
95   for(auto val : *(this->tag_ids))
96     (*this->tag_names)[val.second] = val.first;
97
98   uint32_t max_tag = tag_names->size() - 1;
99   static_bitsequence_builder *bmb = new static_bitsequence_builder_sdarray();
100   alphabet_mapper *am = new alphabet_mapper_none();
101
102   this->tags = new static_sequence_bs((uint32_t*)&((*tags)[0]), npar, am, bmb);
103   bits_per_tag = bits8(max_tag);
104   tag_seq_len = npar;
105   tag_seq = new uint32_t[uint_len(bits_per_tag, tag_seq_len)];
106   for(size_t i = 0; i < (size_t) tag_seq_len; i++)
107     set_field(tag_seq, bits_per_tag, i, (uint32_t) (*tags)[i]);
108
109   delete tags;
110
111   if (disable_tc) {
112     text_positions = 0;
113     text_collection = 0;
114   } else {
115     textbitmap->pack();
116     uint32_t * textbm = textbitmap->get_vector_ptr();
117     text_positions = new static_bitsequence_rrr02(textbm,
118                                                   npar,
119                                                   32);
120     //delete [] textbm;
121     delete textbitmap;
122
123     this->text_index_type = idx_type;
124     fprintf(stderr, "Before!\n");
125     fflush(stderr);
126     text_collection = tc_builder->InitTextCollection();
127     fprintf(stderr, "After!\n");
128     fflush(stderr);
129     delete tc_builder;
130   };
131
132
133 }
134
135 xml_tree::~xml_tree()
136 {
137   bp_delete(par);
138   delete tags;
139   delete [] tag_seq;
140   delete tag_names;
141   delete tag_ids;
142
143   if (text_collection) delete text_collection;
144   if (text_positions) delete text_positions;
145 }
146
147 bool xml_tree::is_child(xml_tree::node_t x, xml_tree::node_t y) const
148 {
149   return !is_leaf(x) && is_ancestor(y, x) && depth(x)+1 == depth(y);
150 }
151
152 uint32_t xml_tree::depth(xml_tree::node_t x) const
153 {
154   return bp_depth(this->par, x);
155 }
156
157
158 uint32_t xml_tree::preorder(xml_tree::node_t x) const
159 {
160   return bp_preorder_rank(this->par, x);
161 }
162
163 uint32_t xml_tree::postorder(xml_tree::node_t x) const
164 {
165   return bp_postorder_rank(this->par, x);
166 }
167
168 xml_tree::node_t
169 xml_tree::select_child(xml_tree::node_t x,
170                        std::unordered_set<tag_t> *tags) const
171 {
172   if (is_nil(x) || is_leaf(x)) return xml_tree::NIL;
173   xml_tree::node_t child = first_child(x);
174   if (tags->find(tag(child)) != tags->end()) return child;
175   return select_sibling(child, tags);
176 }
177
178 xml_tree::node_t
179 xml_tree::select_descendant(xml_tree::node_t x,
180                             std::unordered_set<tag_t> *tags) const
181 {
182   if (is_leaf(x)) return xml_tree::NIL;
183   auto min = xml_tree::NIL;
184   auto aux = xml_tree::NIL;
185   for(auto tag = tags->begin(); tag != tags->end(); ++ tag){
186     aux = tagged_descendant(x, *tag);
187     if ((unsigned int) aux < (unsigned int) min) min = aux;
188   };
189   return min;
190 }
191
192 xml_tree::node_t
193 xml_tree::select_sibling(xml_tree::node_t x,
194                          std::unordered_set<tag_t> *tags) const
195 {
196   xml_tree::node_t sibling = next_sibling(x);
197   xml_tree::tag_t t;
198   while(!is_nil(sibling)) {
199     t = tag(sibling);
200     if (tags->find(t) != tags->end()) return sibling;
201     sibling = next_sibling(sibling);
202   };
203   return sibling;
204 }
205
206 xml_tree::node_t
207 xml_tree::select_following_before(xml_tree::node_t x,
208                                   std::unordered_set<tag_t> *tags,
209                                   xml_tree::node_t limit) const
210 {
211   auto min = xml_tree::NIL;
212   auto aux = xml_tree::NIL;
213   for(auto tag = tags->begin(); tag != tags->end(); ++tag){
214     aux = tagged_following_before(x, *tag, limit);
215     if ((unsigned int) aux < (unsigned int) min) min = aux;
216   }
217   return min;
218 }
219
220 void xml_tree::save(int fd, char* s)
221 {
222   FILE* fp;
223   int fd2 = dup(fd);
224
225   fp = fdopen(fd2, "w");
226
227   if (fd == 0) throw(std::runtime_error(strerror(errno)));
228   saveTree(par, fp); //TODO use new api
229
230   int ntags = tag_names->size();
231
232   ufwrite(&ntags, sizeof(int), 1, fp);
233   for (int i = 0; i < ntags;i++)
234     fprintf(fp, "%s\n", tag_names->at(i).c_str());
235
236   tags->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   fprintf(stderr, "whoot\n");
246   fflush(stderr);
247   if (!disable_tc) {
248     text_positions->save(fp);
249     ufwrite(&text_index_type,
250             sizeof(TextCollectionBuilder::index_type_t),
251             1, fp);
252
253     std::string file(s);
254     switch (text_index_type){
255     case TextCollectionBuilder::index_type_default:
256       file.append("_default");
257       break;
258     case TextCollectionBuilder::index_type_swcsa:
259       file.append("_swcsa");
260       break;
261     case TextCollectionBuilder::index_type_rlcsa:
262       file.append("_rlcsa");
263       break;
264     };
265
266     text_collection->Save(fp, file.c_str());
267   };
268
269   fflush(fp);
270   fclose(fp);
271
272 }
273
274 xml_tree* xml_tree::load(int fd, char* name, bool load_tc, int sf)
275 {
276   FILE *fp;
277   char buffer[1024];
278
279   int i;
280   buffer[1023] = '\0';
281   fp = fdopen(fd, "r");
282   xml_tree *tree = new xml_tree();
283
284   tree->par = loadTree(fp); //TODO use new api
285   tree->tag_names = new std::vector<std::string>();
286   tree->tag_ids = new std::unordered_map<std::string, xml_tree::tag_t>();
287   std::string s;
288   int ntags;
289
290   ufread(&ntags, sizeof(int), 1, fp);
291
292   for (i = 0; i < ntags; i++) {
293     if (fgets(buffer, 1022, fp) != buffer)
294       throw std::runtime_error("xml_tree::load: cannot read tag list");
295     s = buffer;
296     // remove the trailing \n
297     s.erase(s.size()-1);
298     tree->tag_names->push_back(s);
299     tree->tag_ids->insert(std::make_pair(s,
300                                          static_cast<xml_tree::tag_t>(i)));
301
302   };
303
304   tree->tags = static_sequence::load(fp);
305   ufread(&tree->bits_per_tag, sizeof(uint), 1, fp);
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 uint32_t xml_tree::subtree_elements(xml_tree::node_t x) const
349 {
350
351   uint32_t size = bp_subtree_size(par, x);
352   if (x == root()){
353     x = bp_first_child(par,x);
354     size = size - 1;
355   };
356
357   int s = x + 2*size - 1;
358   int ntext =
359     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, s) -
360     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, x-1);
361
362   size = size - ntext;
363   xml_tree::node_t fin = bp_find_close(par, x);
364   xml_tree::node_t y = tags->select_next(xml_tree::ATTRIBUTE_OPEN_TAG_ID, x);
365   while (y != xml_tree::NIL && y < fin){
366     size -= subtree_size(y);
367     y = tags->select_next(xml_tree::ATTRIBUTE_OPEN_TAG_ID, y);
368   };
369   return size;
370  }
371
372 uint32_t xml_tree::num_children(xml_tree::node_t x) const
373 {
374   return bp_degree(par, x);
375 }
376
377 uint32_t xml_tree::child_pos(xml_tree::node_t x) const
378 {
379   return bp_child_rank(par, x);
380 }
381
382 xml_tree::node_t xml_tree::child(xml_tree::node_t x, uint32_t i) const
383 {
384   if (i < 10) return bp_naive_child(par, x, i);
385   else bp_child(par, x, i);
386 }
387
388 std::pair<int32_t, int32_t> xml_tree::text_id_range(xml_tree::node_t x) const
389 {
390   int32_t i, j;
391   i = text_positions->rank1(x - 1);
392   j = text_positions->rank1(x + 2 * bp_subtree_size(par, x) - 2);
393   if (i == j)
394     return std::make_pair(xml_tree::NIL, xml_tree::NIL);
395   else
396     return std::make_pair(i + 1, j);
397 }
398
399 int32_t xml_tree::text_id(xml_tree::node_t x) const
400 {
401   return (int32_t) text_positions->rank1(x) - 1;
402 }
403
404 unsigned char* xml_tree::get_text(int32_t id) const
405 {
406   unsigned char * s = text_collection->GetText(id);
407   return s + (s[0] == 1);
408 }
409
410 void xml_tree::uflush(int fd)
411 {
412   size_t size = print_buffer->size();
413   if (size < BUFFER_SIZE) return;
414   uflush_r(fd, size);
415 }
416 void xml_tree::flush(int fd)
417 {
418   uflush_r(fd, print_buffer->size());
419 }
420
421
422 void xml_tree::uflush_r(int fd, size_t s)
423 {
424   if (s == 0) return;
425   size_t written;
426   while (1) {
427     written = write(fd, print_buffer->data(), s);
428     if ((written < 0) && (errno == EAGAIN || errno == EINTR))
429       continue;
430     break;
431   };
432   print_buffer->clear();
433 }
434 void xml_tree::uput_str(std::string s, int fd)
435 {
436   print_buffer->append(s);
437   uflush(fd);
438 }
439 void xml_tree::uputs(const char* s, int fd)
440 {
441   print_buffer->append(s);
442   uflush(fd);
443 }
444 void xml_tree::uputc(const char c, int fd)
445 {
446   print_buffer->push_back(c);
447   uflush(fd);
448 }
449
450 const char * xml_tree::get_tag_name_by_ref(xml_tree::tag_t tagid) const
451 {
452
453    unsigned char *s;
454    if (tagid < 0 || tagid >= tag_names->size())
455      return "<INVALID TAG>";
456
457    return (const char *) (*tag_names)[tagid].c_str();
458 }
459
460 xml_tree::tag_t xml_tree::register_tag(char *s)
461 {
462   auto found = tag_ids->find(std::string(s));
463   if (found == tag_ids->end())
464     return xml_tree::NIL_TAG_ID;
465   else
466     return (*found).second;
467 }
468
469 size_t xml_tree::uprintf(const char*s, int fd)
470 {
471      if (s == 0) return 0;
472      size_t i;
473      char c;
474      for (i = 0; (c = s[i]); i++) {
475        switch (c) {
476        case '"':
477          uputs("&quot;", fd);
478          break;
479        case '&':
480          uputs("&amp;", fd);
481          break;
482        case '\'':
483          uputs("&apos;", fd);
484          break;
485        case '<':
486          uputs("&lt;", fd);
487          break;
488        case '>':
489          uputs("&gt;", fd);
490          break;
491        default:
492          uputc(c, fd);
493
494        };
495      };
496      return i;
497 }
498
499 void xml_tree::print(int fd, xml_tree::node_t x, bool no_text)
500 {
501   if (print_buffer == 0) {
502     print_buffer = new std::string(BUFFER_SIZE, 0);
503     print_buffer->clear();
504     print_stack = new std::vector<std::string>();
505     print_stack->reserve(256);
506   };
507   xml_tree::node_t fin = bp_find_close(par, x);
508   xml_tree::node_t n = x;
509   xml_tree::tag_t label = tag(n);
510   unsigned char * orig_text;
511   unsigned char * current_text;
512
513   auto r = text_id_range(x);
514   if (r.first == xml_tree::NIL)
515     current_text = 0;
516   else
517     current_text = get_text(r.first);
518
519   orig_text = current_text;
520   size_t read = 0;
521
522   while (n <= fin) {
523
524     if (bp_inspect(par, n)) {
525       if (label == xml_tree::PCDATA_OPEN_TAG_ID){
526         if (no_text) {
527           uputs("<$/>", fd);
528         } else {
529           read = uprintf( (const char*) current_text, fd);
530           current_text += read + 1;
531         };
532         n += 2; // skip closin $
533         label = tag(n);
534       } else {
535
536         uputc('<', fd);
537         uput_str((*tag_names)[label], fd);
538         n++;
539         if (bp_inspect(par, n)) {
540           print_stack->push_back((*tag_names)[label]);
541           label = tag(n);
542           if (label == xml_tree::ATTRIBUTE_OPEN_TAG_ID) {
543             n++;
544             if (no_text) uputs("><@@>", fd);
545
546             while (bp_inspect(par, n))
547               if (no_text) {
548                 uputc('<', fd);
549                 uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
550                 uputc('>', fd);
551                 uputs("<$@/></", fd);
552                 uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
553                 uputc('>', fd);
554                 n += 4;
555               } else {
556                 uputc(' ', fd);
557                 uputs((const char*) &(get_tag_name_by_ref(tag(n))[3]), fd);
558                 n++;
559                 uputs("=\"", fd);
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 }