Optimize subtree_elements by calling find_close only once.
[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   xml_tree::node_t fin = bp_find_close(par, x);
348   uint32_t size = (fin - x)/2;
349   if (x == root()){
350     x = bp_first_child(par,x);
351     size = size - 1;
352   };
353
354   int ntext =
355     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, fin) -
356     tags->rank(xml_tree::PCDATA_OPEN_TAG_ID, x-1);
357
358   size = size - ntext;
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 }