df7efe234fbacc745639e34e22bcecd48a6e3f47
[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     text_collection = tc_builder->InitTextCollection();
125     delete tc_builder;
126   };
127
128
129 }
130
131 xml_tree::~xml_tree()
132 {
133   bp_delete(par);
134   delete tags;
135   delete [] tag_seq;
136   delete tag_names;
137   delete tag_ids;
138
139   if (text_collection) delete text_collection;
140   if (text_positions) delete text_positions;
141 }
142
143 bool xml_tree::is_child(xml_tree::node_t x, xml_tree::node_t y) const
144 {
145   return !is_leaf(x) && is_ancestor(y, x) && depth(x)+1 == depth(y);
146 }
147
148 uint32_t xml_tree::depth(xml_tree::node_t x) const
149 {
150   return bp_depth(this->par, x);
151 }
152
153
154 uint32_t xml_tree::preorder(xml_tree::node_t x) const
155 {
156   return bp_preorder_rank(this->par, x);
157 }
158
159 uint32_t xml_tree::postorder(xml_tree::node_t x) const
160 {
161   return bp_postorder_rank(this->par, x);
162 }
163
164 xml_tree::node_t
165 xml_tree::select_child(xml_tree::node_t x,
166                        std::unordered_set<tag_t> *tags) const
167 {
168   if (is_nil(x) || is_leaf(x)) return xml_tree::NIL;
169   xml_tree::node_t child = first_child(x);
170   if (tags->find(tag(child)) != tags->end()) return child;
171   return select_sibling(child, tags);
172 }
173
174 xml_tree::node_t
175 xml_tree::select_descendant(xml_tree::node_t x,
176                             std::unordered_set<tag_t> *tags) const
177 {
178   if (is_leaf(x)) return xml_tree::NIL;
179   auto min = xml_tree::NIL;
180   auto aux = xml_tree::NIL;
181   for(auto tag = tags->begin(); tag != tags->end(); ++ tag){
182     aux = tagged_descendant(x, *tag);
183     if ((unsigned int) aux < (unsigned int) min) min = aux;
184   };
185   return min;
186 }
187
188 xml_tree::node_t
189 xml_tree::select_sibling(xml_tree::node_t x,
190                          std::unordered_set<tag_t> *tags) const
191 {
192   xml_tree::node_t sibling = next_sibling(x);
193   xml_tree::tag_t t;
194   while(!is_nil(sibling)) {
195     t = tag(sibling);
196     if (tags->find(t) != tags->end()) return sibling;
197     sibling = next_sibling(sibling);
198   };
199   return sibling;
200 }
201
202 xml_tree::node_t
203 xml_tree::select_following_before(xml_tree::node_t x,
204                                   std::unordered_set<tag_t> *tags,
205                                   xml_tree::node_t limit) const
206 {
207   auto min = xml_tree::NIL;
208   auto aux = xml_tree::NIL;
209   for(auto tag = tags->begin(); tag != tags->end(); ++tag){
210     aux = tagged_following_before(x, *tag, limit);
211     if ((unsigned int) aux < (unsigned int) min) min = aux;
212   }
213   return min;
214 }
215
216 void xml_tree::save(int fd, char* s)
217 {
218   FILE* fp;
219   int fd2 = dup(fd);
220
221   fp = fdopen(fd2, "w");
222
223   if (fd == 0) throw(std::runtime_error(strerror(errno)));
224   saveTree(par, fp); //TODO use new api
225
226   int ntags = tag_names->size();
227
228   ufwrite(&ntags, sizeof(int), 1, fp);
229   for (int i = 0; i < ntags;i++)
230     fprintf(fp, "%s\n", tag_names->at(i).c_str());
231
232   tags->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   tree->tags = static_sequence::load(fp);
300   ufread(&tree->bits_per_tag, sizeof(uint), 1, fp);
301   ufread(&tree->tag_seq_len, sizeof(uint), 1, fp);
302   size_t size = uint_len(tree->bits_per_tag, tree->tag_seq_len);
303   tree->tag_seq = new uint[size];
304   ufread(tree->tag_seq, sizeof(uint), size, fp);
305
306   bool disable_tc;
307   ufread(&disable_tc, sizeof(bool), 1, fp);
308
309   if (disable_tc || !load_tc) {
310     tree->text_positions = 0;
311     tree->text_collection = 0;
312   } else {
313
314     tree->text_positions = static_bitsequence_rrr02::load(fp);
315
316     ufread(&tree->text_index_type,
317            sizeof(TextCollectionBuilder::index_type_t), 1, fp);
318
319     std::string file(name);
320     switch (tree->text_index_type){
321     case TextCollectionBuilder::index_type_default:
322       file.append("_default");
323       break;
324     case TextCollectionBuilder::index_type_swcsa:
325       file.append("_swcsa");
326       break;
327     case TextCollectionBuilder::index_type_rlcsa:
328       file.append("_rlcsa");
329       break;
330     };
331
332
333     tree->text_collection =
334       TextCollection::Load(fp,
335                            file.c_str(),
336                            TextCollection::index_mode_default,
337                            sf);
338
339   };
340   return tree;
341 }
342
343 uint32_t xml_tree::subtree_elements(xml_tree::node_t x) const
344 {
345
346   uint32_t size = bp_subtree_size(par, x);
347   if (x == root()){
348     x = bp_first_child(par,x);
349     size = size - 1;
350   };
351
352   int s = x + 2*size - 1;
353   int ntext =
354     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, s) -
355     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, x-1);
356
357   size = size - ntext;
358   xml_tree::node_t fin = bp_find_close(par, x);
359   xml_tree::node_t y = tags->select_next(xml_tree::ATTRIBUTE_OPEN_TAG_ID, x);
360   while (y != xml_tree::NIL && y < fin){
361     size -= subtree_size(y);
362     y = tags->select_next(xml_tree::ATTRIBUTE_OPEN_TAG_ID, y);
363   };
364   return size;
365  }
366
367 uint32_t xml_tree::num_children(xml_tree::node_t x) const
368 {
369   return bp_degree(par, x);
370 }
371
372 uint32_t xml_tree::child_pos(xml_tree::node_t x) const
373 {
374   return bp_child_rank(par, x);
375 }
376
377 xml_tree::node_t xml_tree::child(xml_tree::node_t x, uint32_t i) const
378 {
379   if (i < 10) return bp_naive_child(par, x, i);
380   else bp_child(par, x, i);
381 }
382
383 std::pair<int32_t, int32_t> xml_tree::text_id_range(xml_tree::node_t x) const
384 {
385   int32_t i, j;
386   i = text_positions->rank1(x - 1);
387   j = text_positions->rank1(x + 2 * bp_subtree_size(par, x) - 2);
388   if (i == j)
389     return std::make_pair(xml_tree::NIL, xml_tree::NIL);
390   else
391     return std::make_pair(i + 1, j);
392 }
393
394 int32_t xml_tree::text_id(xml_tree::node_t x) const
395 {
396   return (int32_t) text_positions->rank1(x) - 1;
397 }
398
399 unsigned char* xml_tree::get_text(int32_t id) const
400 {
401   unsigned char * s = text_collection->GetText(id);
402   return s + (s[0] == 1);
403 }
404
405 void xml_tree::uflush(int fd)
406 {
407   size_t size = print_buffer->size();
408   if (size < BUFFER_SIZE) return;
409   uflush_r(fd, size);
410 }
411
412 void xml_tree::flush(int fd)
413 {
414   uflush_r(fd, print_buffer->size());
415 }
416
417
418 void xml_tree::uflush_r(int fd, size_t s)
419 {
420   if (s == 0) return;
421   size_t written;
422   while (1) {
423     written = write(fd, print_buffer->data(), s);
424     if ((written < 0) && (errno == EAGAIN || errno == EINTR)){
425       continue;
426     };
427     break;
428   };
429   print_buffer->clear();
430 }
431
432 void xml_tree::uput_str(std::string s, int fd)
433 {
434   print_buffer->append(s);
435   uflush(fd);
436 }
437 void xml_tree::uputs(const char* s, int fd)
438 {
439   print_buffer->append(s);
440   uflush(fd);
441 }
442 void xml_tree::uputc(const char c, int fd)
443 {
444   print_buffer->push_back(c);
445   uflush(fd);
446 }
447
448 const char * xml_tree::get_tag_name_by_ref(xml_tree::tag_t tagid) const
449 {
450
451    unsigned char *s;
452    if (tagid < 0 || tagid >= tag_names->size())
453      return "<INVALID TAG>";
454
455    return (const char *) (*tag_names)[tagid].c_str();
456 }
457
458 xml_tree::tag_t xml_tree::register_tag(char *s)
459 {
460   auto found = tag_ids->find(std::string(s));
461   if (found == tag_ids->end())
462     return xml_tree::NIL_TAG_ID;
463   else
464     return (*found).second;
465 }
466
467 size_t xml_tree::uprintf(const char*s, int fd)
468 {
469      if (s == 0) return 0;
470      size_t i;
471      char c;
472      for (i = 0; (c = s[i]); i++) {
473        switch (c) {
474        case '"':
475          uputs("&quot;", fd);
476          break;
477        case '&':
478          uputs("&amp;", fd);
479          break;
480        case '\'':
481          uputs("&apos;", fd);
482          break;
483        case '<':
484          uputs("&lt;", fd);
485          break;
486        case '>':
487          uputs("&gt;", fd);
488          break;
489        default:
490          uputc(c, fd);
491
492        };
493      };
494      return i;
495 }
496
497 void xml_tree::print(xml_tree::node_t x, int fd, bool no_text)
498 {
499
500   if (print_buffer == 0) {
501     print_buffer = new std::string(BUFFER_SIZE, 0);
502     print_buffer->clear();
503     print_stack = new std::vector<std::string>();
504     print_stack->reserve(256);
505   };
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 }