8c0386e4497ef57a577f392be272972ab32e32db
[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
93   par = bp_construct(npar,
94                      parbitmap->get_vector_ptr(),
95                      OPT_DEGREE);
96   delete parbitmap;
97
98   this->tag_ids = tag_ids;
99   tag_names = new std::vector<std::string>();
100   tag_names->resize(tag_ids->size());
101   for(auto val : *(this->tag_ids))
102     (*this->tag_names)[val.second] = val.first;
103
104   uint32_t max_tag = tag_names->size() - 1;
105   static_bitsequence_builder *bmb = new static_bitsequence_builder_sdarray();
106   alphabet_mapper *am = new alphabet_mapper_none();
107
108   this->tags = new static_sequence_bs((uint32_t*)&((*tags)[0]), npar, am, bmb);
109   bits_per_tag = bits8(max_tag);
110   tag_seq_len = npar;
111   tag_seq = new uint32_t[uint_len(bits_per_tag, tag_seq_len)];
112   for(size_t i = 0; i < (size_t) tag_seq_len; i++)
113     set_field(tag_seq, bits_per_tag, i, (uint32_t) (*tags)[i]);
114
115   delete tags;
116
117   if (disable_tc) {
118     text_positions = 0;
119     text_collection = 0;
120   } else {
121     textbitmap->pack();
122     uint32_t * textbm = textbitmap->get_vector_ptr();
123     text_positions = new static_bitsequence_rrr02(textbm,
124                                                   npar,
125                                                   32);
126     //delete [] textbm;
127     delete textbitmap;
128
129     this->text_index_type = idx_type;
130     text_collection = tc_builder->InitTextCollection();
131     delete tc_builder;
132   };
133
134
135 }
136
137 xml_tree::~xml_tree()
138 {
139   bp_delete(par);
140   delete tags;
141   delete [] tag_seq;
142   delete tag_names;
143   delete tag_ids;
144
145   if (text_collection) delete text_collection;
146   if (text_positions) delete text_positions;
147 }
148
149 bool xml_tree::is_child(xml_tree::node_t x, xml_tree::node_t y) const
150 {
151   return !is_leaf(x) && is_ancestor(y, x) && depth(x)+1 == depth(y);
152 }
153
154 uint32_t xml_tree::depth(xml_tree::node_t x) const
155 {
156   return bp_depth(this->par, x);
157 }
158
159
160 uint32_t xml_tree::preorder(xml_tree::node_t x) const
161 {
162   return bp_preorder_rank(this->par, x);
163 }
164
165 uint32_t xml_tree::postorder(xml_tree::node_t x) const
166 {
167   return bp_postorder_rank(this->par, x);
168 }
169
170 xml_tree::node_t
171 xml_tree::select_child(xml_tree::node_t x, xml_tree::tag_t *tags) const
172 {
173   if (is_nil(x) || is_leaf(x)) return xml_tree::NIL;
174   xml_tree::node_t child = first_child(x);
175   if (array_mem(tags, tag(child))) return child;
176   return select_sibling(child, tags);
177 }
178
179 xml_tree::node_t
180 xml_tree::select_descendant(xml_tree::node_t x, xml_tree::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(; *tags != xml_tree::NIL_TAG_ID; ++tags){
186     aux = tagged_descendant(x, *tags);
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, xml_tree::tag_t *tags) const
194 {
195   xml_tree::node_t sibling = next_sibling(x);
196   xml_tree::tag_t t;
197   while(!is_nil(sibling)) {
198     t = tag(sibling);
199     if (array_mem(tags, t)) return sibling;
200     sibling = next_sibling(sibling);
201   };
202   return sibling;
203 }
204
205 xml_tree::node_t
206 xml_tree::select_following_before(xml_tree::node_t x, xml_tree::tag_t *tags,
207                                   xml_tree::node_t limit) const
208 {
209   auto min = xml_tree::NIL;
210   auto aux = xml_tree::NIL;
211   for(; *tags != xml_tree::NIL_TAG_ID; ++tags){
212     aux = tagged_following_before(x, *tags, limit);
213     if ((unsigned int) aux < (unsigned int) min) min = aux;
214   }
215   return min;
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
236   ufwrite(&bits_per_tag, sizeof(uint),1,fp);
237   ufwrite(&tag_seq_len, sizeof(uint),1,fp);
238   ufwrite(tag_seq, sizeof(uint), uint_len(bits_per_tag, tag_seq_len), fp);
239
240   bool disable_tc = text_collection == 0 || text_positions == 0;
241
242   ufwrite(&disable_tc, sizeof(bool),1,fp);
243
244   if (!disable_tc) {
245     text_positions->save(fp);
246     ufwrite(&text_index_type,
247             sizeof(TextCollectionBuilder::index_type_t),
248             1, fp);
249
250     std::string file(s);
251     switch (text_index_type){
252     case TextCollectionBuilder::index_type_default:
253       file.append("_default");
254       break;
255     case TextCollectionBuilder::index_type_swcsa:
256       file.append("_swcsa");
257       break;
258     case TextCollectionBuilder::index_type_rlcsa:
259       file.append("_rlcsa");
260       break;
261     };
262
263     text_collection->Save(fp, file.c_str());
264   };
265
266   fflush(fp);
267   fclose(fp);
268
269 }
270
271 xml_tree* xml_tree::load(int fd, char* name, bool load_tc, int sf)
272 {
273   FILE *fp;
274   char buffer[1024];
275
276   int i;
277   buffer[1023] = '\0';
278   fp = fdopen(fd, "r");
279   xml_tree *tree = new xml_tree();
280
281   tree->par = loadTree(fp); //TODO use new api
282   tree->tag_names = new std::vector<std::string>();
283   tree->tag_ids = new std::unordered_map<std::string, xml_tree::tag_t>();
284   std::string s;
285   int ntags;
286
287   ufread(&ntags, sizeof(int), 1, fp);
288
289   for (i = 0; i < ntags; i++) {
290     if (fgets(buffer, 1022, fp) != buffer)
291       throw std::runtime_error("xml_tree::load: cannot read tag list");
292     s = buffer;
293     // remove the trailing \n
294     s.erase(s.size()-1);
295     tree->tag_names->push_back(s);
296     tree->tag_ids->insert(std::make_pair(s,
297                                          static_cast<xml_tree::tag_t>(i)));
298
299   };
300
301   tree->tags = static_sequence::load(fp);
302   ufread(&tree->bits_per_tag, sizeof(uint), 1, fp);
303   ufread(&tree->tag_seq_len, sizeof(uint), 1, fp);
304   size_t size = uint_len(tree->bits_per_tag, tree->tag_seq_len);
305   tree->tag_seq = new uint[size];
306   ufread(tree->tag_seq, sizeof(uint), size, fp);
307
308   bool disable_tc;
309   ufread(&disable_tc, sizeof(bool), 1, fp);
310
311   if (disable_tc || !load_tc) {
312     tree->text_positions = 0;
313     tree->text_collection = 0;
314   } else {
315
316     tree->text_positions = static_bitsequence_rrr02::load(fp);
317
318     ufread(&tree->text_index_type,
319            sizeof(TextCollectionBuilder::index_type_t), 1, fp);
320
321     std::string file(name);
322     switch (tree->text_index_type){
323     case TextCollectionBuilder::index_type_default:
324       file.append("_default");
325       break;
326     case TextCollectionBuilder::index_type_swcsa:
327       file.append("_swcsa");
328       break;
329     case TextCollectionBuilder::index_type_rlcsa:
330       file.append("_rlcsa");
331       break;
332     };
333
334
335     tree->text_collection =
336       TextCollection::Load(fp,
337                            file.c_str(),
338                            TextCollection::index_mode_default,
339                            sf);
340
341   };
342   return tree;
343 }
344
345 uint32_t xml_tree::subtree_elements(xml_tree::node_t x) const
346 {
347
348   uint32_t size = bp_subtree_size(par, x);
349   if (x == root()){
350     x = bp_first_child(par,x);
351     size = size - 1;
352   };
353
354   int s = x + 2*size - 1;
355   int ntext =
356     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, s) -
357     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, x-1);
358
359   size = size - ntext;
360   xml_tree::node_t fin = bp_find_close(par, x);
361   xml_tree::node_t y = tags->select_next(xml_tree::ATTRIBUTE_OPEN_TAG_ID, x);
362   while (y != xml_tree::NIL && y < fin){
363     size -= subtree_size(y);
364     y = tags->select_next(xml_tree::ATTRIBUTE_OPEN_TAG_ID, y);
365   };
366   return size;
367  }
368
369 uint32_t xml_tree::num_children(xml_tree::node_t x) const
370 {
371   return bp_degree(par, x);
372 }
373
374 uint32_t xml_tree::child_pos(xml_tree::node_t x) const
375 {
376   return bp_child_rank(par, x);
377 }
378
379 xml_tree::node_t xml_tree::child(xml_tree::node_t x, uint32_t i) const
380 {
381   if (i < 10) return bp_naive_child(par, x, i);
382   else bp_child(par, x, i);
383 }
384
385 std::pair<int32_t, int32_t> xml_tree::text_id_range(xml_tree::node_t x) const
386 {
387   int32_t i, j;
388   i = text_positions->rank1(x - 1);
389   j = text_positions->rank1(x + 2 * bp_subtree_size(par, x) - 2);
390   if (i == j)
391     return std::make_pair(xml_tree::NIL, xml_tree::NIL);
392   else
393     return std::make_pair(i + 1, j);
394 }
395
396 int32_t xml_tree::text_id(xml_tree::node_t x) const
397 {
398   return (int32_t) text_positions->rank1(x) - 1;
399 }
400
401 unsigned char* xml_tree::get_text(int32_t id) const
402 {
403   unsigned char * s = text_collection->GetText(id);
404   return s + (s[0] == 1);
405 }
406
407 void xml_tree::uflush(int fd)
408 {
409   size_t size = print_buffer->size();
410   if (size < BUFFER_SIZE) return;
411   uflush_r(fd, size);
412 }
413
414 void xml_tree::flush(int fd)
415 {
416   uflush_r(fd, print_buffer->size());
417 }
418
419
420 void xml_tree::uflush_r(int fd, size_t s)
421 {
422   if (s == 0) return;
423   size_t written;
424   while (1) {
425     written = write(fd, print_buffer->data(), s);
426     if ((written < 0) && (errno == EAGAIN || errno == EINTR)){
427       continue;
428     };
429     break;
430   };
431   print_buffer->clear();
432 }
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(xml_tree::node_t x, int fd, bool no_text)
500 {
501
502   if (print_buffer == 0) {
503     print_buffer = new std::string(BUFFER_SIZE, 0);
504     print_buffer->clear();
505     print_stack = new std::vector<std::string>();
506     print_stack->reserve(256);
507   };
508
509   xml_tree::node_t fin = bp_find_close(par, x);
510   xml_tree::node_t n = x;
511   xml_tree::tag_t label = tag(n);
512   unsigned char * orig_text;
513   unsigned char * current_text;
514
515   auto r = text_id_range(x);
516   if (r.first == xml_tree::NIL)
517     current_text = 0;
518   else
519     current_text = get_text(r.first);
520
521   orig_text = current_text;
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 }