Merge branch 'local-ocamlbuild' into local-trunk
[SXSI/xpathcomp.git] / src / OCamlDriver.cpp
1 /**************************************
2  * OCamlDriver.cpp
3  * -------------------
4  * An Ocaml Driver which calls the C++ methods and
5  * adds a C wrapper interface with OCaml code.
6  *
7  * Author: Kim Nguyen
8  * Date: 04/11/08
9  */
10
11 /***
12  *  Conventions:
13  *  functions never doing any allocation (non caml_alloc*, caml_copy_string,...)
14  *  have NOALLOC in the comment and their external declaration can have "noalloc"
15  */
16
17
18 #include <unordered_set>
19 #include <algorithm>
20 #include "XMLDocShredder.h"
21 #include "XMLTree.h"
22 #include "Utils.h"
23
24 extern "C" {
25 /* OCaml memory managment */
26 #include <caml/mlvalues.h>
27 #include <caml/alloc.h>
28 #include <caml/memory.h>
29 #include <caml/callback.h>
30 #include <caml/fail.h>
31 #include <caml/custom.h>
32 #include <caml/bigarray.h>
33   //#include "results.h"
34 #include <stdio.h>
35
36 #define CAMLRAISEMSG(msg) (caml_raise_with_string(*cpp_exception,(msg) ))
37 #define NOT_IMPLEMENTED(s)  (caml_failwith(s))
38 #define XMLTREE(x) ((XMLTree *)(* (XMLTree**) Data_custom_val(x)))
39 #define HSET(x) ((TagIdSet*)((* (TagIdSet**) Data_custom_val(x))))
40 #define TEXTCOLLECTION(x)
41 #define TREENODEVAL(i) ((treeNode) (Int_val(i)))
42 #define TAGVAL(i) ((TagType) (Int_val(i)))
43 #define XMLTREE_ROOT 0
44 #define NoAlloc
45
46
47   static struct custom_operations ops;
48   static struct custom_operations set_ops;
49   static value * cpp_exception = NULL;
50   static bool ops_initialized = false;
51
52 #include <sys/time.h>
53 #include <sys/resource.h>
54
55
56 }
57
58 extern "C" void caml_xml_tree_finalize(value tree){
59   delete XMLTREE(tree);
60   return;
61 }
62
63 extern "C" void caml_hset_finalize(value hblock){
64   delete HSET(hblock);
65   return;
66 }
67
68 extern "C"  value caml_init_lib (value unit) {
69   CAMLparam1(unit);
70
71   struct rlimit rlim;
72
73   if (!ops_initialized){
74
75     getrlimit(RLIMIT_STACK, &rlim);
76
77     if (rlim.rlim_max == RLIM_INFINITY && rlim.rlim_cur != RLIM_INFINITY) {
78       rlim.rlim_cur = RLIM_INFINITY;
79       setrlimit(RLIMIT_STACK, &rlim);
80     };
81
82     ops.identifier = (char*) "XMLTree";
83     ops.finalize = caml_xml_tree_finalize;
84     set_ops.identifier = (char*) "unordered_set";
85     set_ops.finalize = caml_hset_finalize;
86
87     cpp_exception = caml_named_value("CPlusPlusError");
88     if (cpp_exception == NULL){
89       string s = "FATAL: Unregistered exception ";
90     s += "CPlusPlusError";
91     caml_failwith(s.c_str());
92     };
93
94     ops_initialized = true;
95
96   };
97   CAMLreturn(Val_unit);
98
99 }
100
101 extern "C"  value caml_shredder_parse(XMLDocShredder *shredder){
102   CAMLparam0();
103   CAMLlocal1(doc);
104   XMLTree * tree;
105   shredder->processStartDocument("");
106   shredder->parse();
107   shredder->processEndDocument();
108   doc = caml_alloc_custom(&ops,sizeof(XMLTree*),1,2);
109   tree = (XMLTree *) shredder->getXMLTree();
110   memcpy(Data_custom_val(doc),&tree,sizeof(XMLTree*));
111   CAMLreturn(doc);
112
113 }
114
115 extern "C"  value caml_call_shredder_uri(value uri,value sf, value iet, value dtc, value idtype){
116   CAMLparam1(uri);
117   CAMLlocal1(doc);
118   char *fn = String_val(uri);
119   XMLDocShredder * shredder;
120   TextCollectionBuilder::index_type_t id;
121   switch (Int_val(idtype)){
122   case 0:
123     id = TextCollectionBuilder::index_type_default;
124     break;
125   case 1:
126     id = TextCollectionBuilder::index_type_swcsa;
127     break;
128   case 2:
129     id = TextCollectionBuilder::index_type_rlcsa;
130     break;
131   default:
132     CAMLRAISEMSG("");
133   };
134
135   try {
136     shredder = new XMLDocShredder(fn,Int_val(sf),Bool_val(iet),Bool_val(dtc), id);
137     doc = caml_shredder_parse(shredder);
138     delete shredder;
139   }
140   catch (const std::exception& e){ CAMLRAISEMSG(e.what()); }
141   catch (string  msg){  CAMLRAISEMSG(msg.c_str()); }
142   catch (char const * msg){ CAMLRAISEMSG(msg);  };
143   CAMLreturn (doc);
144
145 }
146 extern "C"  value caml_call_shredder_string(value data,value sf, value iet, value dtc, value idtype){
147   CAMLparam1(data);
148   CAMLlocal1(doc);
149   XMLDocShredder * shredder;
150   unsigned int ln = caml_string_length(data);
151   unsigned char *fn = (unsigned char*) String_val(data);
152   TextCollectionBuilder::index_type_t id;
153   switch (Int_val(idtype)){
154   case 0:
155     id = TextCollectionBuilder::index_type_default;
156     break;
157   case 1:
158     id = TextCollectionBuilder::index_type_swcsa;
159     break;
160   case 2:
161     id = TextCollectionBuilder::index_type_rlcsa;
162     break;
163   default:
164     CAMLRAISEMSG("");
165   };
166
167   try {
168
169     shredder = new  XMLDocShredder (fn,ln,Int_val(sf),Bool_val(iet),Bool_val(dtc), id);
170     doc = caml_shredder_parse(shredder);
171     delete shredder;
172   }
173   catch (const std::exception& e){ CAMLRAISEMSG(e.what()); }
174   catch (string  msg){  CAMLRAISEMSG(msg.c_str()); }
175   catch (char const * msg){ CAMLRAISEMSG(msg);  };
176   CAMLreturn(doc);
177 }
178
179 extern "C"  value caml_xml_tree_save(value tree,value fd, value name){
180   CAMLparam3(tree, fd, name);
181   XMLTREE(tree)->Save(Int_val(fd), String_val(name));
182   CAMLreturn (Val_unit);
183 }
184
185 extern "C"  value caml_xml_tree_load(value fd, value name, value load_tc,value sf){
186   CAMLparam4(fd, name, load_tc, sf);
187   CAMLlocal1(doc);
188   XMLTree * tree;
189   try {
190     tree = XMLTree::Load(Int_val(fd),Bool_val(load_tc),Int_val(sf), String_val(name));
191     doc = caml_alloc_custom(&ops,sizeof(XMLTree*),1,2);
192     memcpy(Data_custom_val(doc),&tree,sizeof(XMLTree*));
193     CAMLreturn(doc);
194   }
195   catch (const xmlpp::internal_error& e){ CAMLRAISEMSG(e.what()); }
196   catch (const std::exception& e){ CAMLRAISEMSG(e.what()); }
197   catch (string  msg){  CAMLRAISEMSG(msg.c_str()); }
198   catch (char const * msg){ CAMLRAISEMSG(msg);  };
199 }
200
201
202
203 /*************************************************************************/
204
205 /**
206  *  XMLTree bindings
207  *  All of the functions here call the _unsafe version and implement the logics themselves
208  *  (test for NULLT and so on). This avoids one indirection + one call when the tests fails.
209  */
210
211
212 NoAlloc extern "C"  value caml_xml_tree_root(value tree){
213   return (Val_int(XMLTREE_ROOT));
214 }
215
216 NoAlloc extern "C"  value caml_xml_tree_size(value tree){
217   return (Val_int(XMLTREE(tree)->Size()));
218 }
219
220 NoAlloc extern "C"  value caml_xml_tree_num_tags(value tree){
221   return (Val_int(XMLTREE(tree)->NumTags()));
222 }
223
224 NoAlloc extern "C"  value caml_xml_tree_subtree_size(value tree, value node){
225   return (Val_int(XMLTREE(tree)->SubtreeSize(TREENODEVAL(node))));
226 }
227
228 NoAlloc extern "C"  value caml_xml_tree_subtree_tags(value tree, value node, value tag){
229   return (Val_int(XMLTREE(tree)->SubtreeTags(TREENODEVAL(node), TAGVAL(tag))));
230 }
231
232 NoAlloc extern "C"  value caml_xml_tree_subtree_elements(value tree, value node){
233   return (Val_int(XMLTREE(tree)->SubtreeElements(TREENODEVAL(node))));
234 }
235
236 NoAlloc extern "C"  value caml_xml_tree_is_leaf(value tree, value node){
237   return (Val_bool(XMLTREE(tree)->IsLeaf(TREENODEVAL(node))));
238 }
239
240 NoAlloc extern "C"  value caml_xml_tree_is_ancestor(value tree, value node1,value node2){
241   return (Val_bool(XMLTREE(tree)->IsAncestor(TREENODEVAL(node1),TREENODEVAL(node2))));
242 }
243
244 NoAlloc extern "C"  value caml_xml_tree_is_child(value tree, value node1,value node2){
245   return (Val_bool(XMLTREE(tree)->IsChild(TREENODEVAL(node1),TREENODEVAL(node2))));
246 }
247
248 NoAlloc extern "C"  value caml_xml_tree_is_first_child(value tree, value node){
249   return (Val_bool(XMLTREE(tree)->IsFirstChild(TREENODEVAL(node))));
250 }
251 NoAlloc extern "C"  value caml_xml_tree_is_right_descendant(value tree, value x, value y){
252   return (Val_bool(XMLTREE(tree)->IsRightDescendant(TREENODEVAL(x), TREENODEVAL(y))));
253 }
254 NoAlloc extern "C"  value caml_xml_tree_num_children(value tree, value node){
255   return (Val_int(XMLTREE(tree)->NumChildren(TREENODEVAL(node))));
256 }
257
258 NoAlloc extern "C"  value caml_xml_tree_child_number(value tree, value node){
259   return (Val_int(XMLTREE(tree)->ChildNumber(TREENODEVAL(node))));
260 }
261
262 NoAlloc extern "C"  value caml_xml_tree_depth(value tree, value node){
263   return (Val_int(XMLTREE(tree)->Depth(TREENODEVAL(node))));
264 }
265
266 NoAlloc extern "C"  value caml_xml_tree_preorder(value tree, value node){
267   return (Val_int(XMLTREE(tree)->Preorder(TREENODEVAL(node))));
268 }
269
270 NoAlloc extern "C"  value caml_xml_tree_postorder(value tree, value node){
271   return (Val_int(XMLTREE(tree)->Postorder(TREENODEVAL(node))));
272 }
273
274 NoAlloc extern "C"  value caml_xml_tree_tag(value tree, value node) throw () {
275   return (Val_int(XMLTREE(tree)->Tag(TREENODEVAL(node))));
276 }
277
278 extern "C"  value caml_xml_tree_doc_ids(value tree, value node){
279   CAMLparam2(tree,node);
280   CAMLlocal1(tuple);
281   range ids;
282   tuple = caml_alloc(2,0);
283   ids = XMLTREE(tree)->DocIds(Int_val(node));
284   Store_field(tuple,0,Val_int(ids.min));
285   Store_field(tuple,1,Val_int(ids.max));
286   CAMLreturn (tuple);
287 }
288
289 NoAlloc extern "C"  value caml_xml_tree_parent(value tree, value node){
290   return (Val_int(XMLTREE(tree)->Parent(TREENODEVAL(node))));
291 }
292
293 NoAlloc extern "C"  value caml_xml_tree_binary_parent(value tree, value node){
294   return (Val_int(XMLTREE(tree)->BinaryParent(TREENODEVAL(node))));
295 }
296
297 NoAlloc extern "C"  value caml_xml_tree_child(value tree, value node,value idx){
298   return (Val_int(XMLTREE(tree)->Child(TREENODEVAL(node),Int_val(idx))));
299 }
300
301 NoAlloc extern "C"  value caml_xml_tree_first_child(value tree, value node){
302   return (Val_int(XMLTREE(tree)->FirstChild(TREENODEVAL(node))));
303 }
304
305 NoAlloc extern "C"  value caml_xml_tree_first_element(value tree, value node){
306   return (Val_int(XMLTREE(tree)->FirstElement(TREENODEVAL(node))));
307 }
308
309 NoAlloc extern "C"  value caml_xml_tree_last_child(value tree, value node){
310   return (Val_int(XMLTREE(tree)->LastChild(TREENODEVAL(node))));
311 }
312
313 NoAlloc extern "C"  value caml_xml_tree_next_sibling(value tree, value node){
314   return (Val_int(XMLTREE(tree)->NextSibling(TREENODEVAL(node))));
315 }
316
317 NoAlloc extern "C"  value caml_xml_tree_next_element(value tree, value node){
318   return (Val_int(XMLTREE(tree)->NextElement(TREENODEVAL(node))));
319 }
320
321 NoAlloc extern "C"  value caml_xml_tree_prev_sibling(value tree, value node){
322   return (Val_int(XMLTREE(tree)->PrevSibling(TREENODEVAL(node))));
323 }
324
325 NoAlloc extern "C"  value caml_xml_tree_tagged_child(value tree, value node,value tag){
326   return (Val_int(XMLTREE(tree)->TaggedChild(TREENODEVAL(node),TAGVAL(tag))));
327 }
328
329 NoAlloc extern "C"  value caml_xml_tree_select_child(value tree, value node,value tags){
330   return (Val_int(XMLTREE(tree)->SelectChild(TREENODEVAL(node), HSET(tags))));
331 }
332
333 NoAlloc extern "C"  value caml_xml_tree_tagged_following_sibling(value tree, value node,value tag){
334   return (Val_int(XMLTREE(tree)->TaggedFollowingSibling(TREENODEVAL(node),TAGVAL(tag))));
335 }
336
337 NoAlloc extern "C"  value caml_xml_tree_select_following_sibling(value tree, value node,value tags){
338   return (Val_int(XMLTREE(tree)->SelectFollowingSibling(TREENODEVAL(node), HSET(tags))));
339 }
340
341 NoAlloc extern "C"  value caml_xml_tree_tagged_descendant(value tree, value node, value tag){
342   return (Val_int(XMLTREE(tree)->TaggedDescendant(TREENODEVAL(node), TAGVAL(tag))));
343 }
344
345 NoAlloc extern "C"  value caml_xml_tree_select_descendant(value tree, value node, value tags){
346   return (Val_int(XMLTREE(tree)->SelectDescendant(TREENODEVAL(node), HSET(tags))));
347 }
348
349 NoAlloc extern "C"  value caml_xml_tree_tagged_preceding(value tree, value node, value tag){
350   return (Val_int(XMLTREE(tree)->TaggedPreceding(TREENODEVAL(node), TAGVAL(tag))));
351 }
352
353 NoAlloc extern "C"  value caml_xml_tree_tagged_following(value tree, value node, value tag){
354   return (Val_int(XMLTREE(tree)->TaggedFollowing(TREENODEVAL(node), TAGVAL(tag))));
355 }
356
357 NoAlloc extern "C"  value caml_xml_tree_tagged_following_below(value tree, value node, value tag, value ancestor){
358   return (Val_int(XMLTREE(tree)->TaggedFollowingBelow(TREENODEVAL(node), TAGVAL(tag), TREENODEVAL(ancestor))));
359 }
360
361 NoAlloc extern "C"  value caml_xml_tree_select_following_below(value tree, value node, value tags, value ancestor){
362   return (Val_int(XMLTREE(tree)->SelectFollowingBelow(TREENODEVAL(node), HSET(tags), TREENODEVAL(ancestor))));
363 }
364
365 NoAlloc extern "C"  value caml_xml_tree_tagged_following_before(value tree, value node, value tag, value closing){
366   return (Val_int(XMLTREE(tree)->TaggedFollowingBefore(TREENODEVAL(node), TAGVAL(tag), TREENODEVAL(closing))));
367 }
368
369 NoAlloc extern "C"  value caml_xml_tree_select_following_before(value tree, value node, value tags, value closing){
370   return (Val_int(XMLTREE(tree)->SelectFollowingBefore(TREENODEVAL(node), HSET(tags), TREENODEVAL(closing))));
371 }
372
373 NoAlloc extern "C"  value caml_xml_tree_tagged_ancestor(value tree, value node, value tag){
374   return (Val_int(XMLTREE(tree)->TaggedAncestor(TREENODEVAL(node), TAGVAL(tag))));
375 }
376
377 NoAlloc extern "C"  value caml_xml_tree_my_text(value tree, value node){
378   return (Val_int(XMLTREE(tree)->MyText(TREENODEVAL(node))));
379 }
380
381 NoAlloc extern "C"  value caml_xml_tree_my_text_unsafe(value tree, value node){
382   return (Val_int(XMLTREE(tree)->MyTextUnsafe(TREENODEVAL(node))));
383 }
384
385 NoAlloc extern "C"  value caml_xml_tree_text_xml_id(value tree, value docid){
386   return (Val_int(XMLTREE(tree)->TextXMLId(Int_val(docid))));
387 }
388
389 NoAlloc extern "C"  value caml_xml_tree_node_xml_id(value tree, value node){
390   return (Val_int(XMLTREE(tree)->NodeXMLId(TREENODEVAL(node))));
391 }
392
393 NoAlloc extern "C"  value caml_xml_tree_parent_node(value tree, value docid){
394   return (Val_int(XMLTREE(tree)->ParentNode(Int_val(docid))));
395 }
396 /*
397 NoAlloc extern "C"  value caml_xml_tree_prev_node(value tree, value docid){
398   return (Val_int(XMLTREE(tree)->PrevNode(Int_val(docid))));
399 }
400 */
401 extern "C"  value caml_xml_tree_get_tag_id(value tree, value tagname){
402   CAMLparam2(tree,tagname);
403   CAMLlocal1(res);
404   unsigned char* ctagname = (unsigned char*) strdup(String_val(tagname));
405   res = Val_int(XMLTREE(tree)->GetTagId(ctagname));
406   free(ctagname);
407   CAMLreturn(res);
408 }
409
410 extern "C"  value caml_xml_tree_get_tag_name(value tree, value tag){
411   CAMLparam2(tree,tag);
412   CAMLlocal1(res);
413   res = caml_copy_string((const char*) XMLTREE(tree)->GetTagNameByRef(TAGVAL(tag)));
414   CAMLreturn(res);
415 }
416
417 extern "C"  value caml_xml_tree_register_tag(value tree, value tagname){
418   CAMLparam2(tree,tagname);
419   CAMLlocal1(res);
420   unsigned char* ctagname = (unsigned char*) strdup(String_val(tagname));
421   res = Val_int(XMLTREE(tree)->RegisterTag(ctagname));
422   free(ctagname);
423   CAMLreturn(res);
424 }
425
426
427 NoAlloc extern "C"  value caml_xml_tree_get_text_collection(value tree){
428   return((value) XMLTREE(tree)->getTextCollection());
429 }
430
431 NoAlloc extern "C"  value caml_xml_tree_closing(value tree, value node){
432   return (Val_int(XMLTREE(tree)->Closing(TREENODEVAL(node))));
433 }
434
435 NoAlloc extern "C"  value caml_xml_tree_is_open(value tree, value node){
436   return (Val_bool(XMLTREE(tree)->IsOpen(TREENODEVAL(node))));
437 }
438
439
440
441 NoAlloc extern "C"  value caml_xml_tree_nullt(value unit){
442   return (NULLT);
443 }
444
445
446 NoAlloc extern "C"  value caml_unordered_set_length(value hset){
447   return (Val_int((HSET(hset))->size()));
448 }
449
450 extern "C"  value caml_unordered_set_alloc(value unit){
451   CAMLparam1(unit);
452   CAMLlocal1(hset);
453   hset = caml_alloc_custom(&set_ops,sizeof(TagIdSet*),1,2);
454   TagIdSet* ht = new TagIdSet();
455   memcpy(Data_custom_val(hset),&ht,sizeof(TagIdSet*));
456   CAMLreturn (hset);
457 }
458
459 NoAlloc extern "C"  value caml_unordered_set_set(value set, value v){
460   HSET(set)->insert((int) Int_val(v));
461   return (Val_unit);
462 }
463
464 // NoAlloc extern "C" value caml_result_set_create(value size){
465 //   results* res = (results*) malloc(sizeof(results));
466 //   results r = createResults (Int_val(size));
467 //   res->n = r.n;
468 //   res->lgn = r.lgn;
469 //   res->tree = r.tree;
470 //   return ((value) (res));
471 // }
472
473 // NoAlloc extern "C"  value caml_result_set_set(value result,value p){
474 //   setResult (  *((results*) result), Int_val(p));
475 //   return (Val_unit);
476 // }
477
478 // NoAlloc extern "C"  value caml_result_set_clear(value result,value p1,value p2){
479 //   clearRange ( *((results*) result), Int_val(p1), Int_val(p2));
480 //   return (Val_unit);
481 // }
482
483 // NoAlloc extern "C"  value caml_result_set_next(value result,value p){
484 //   results r;
485 //   r = *( (results *) result);
486 //   return (Val_int(nextResult(r, Int_val(p))));
487 // }
488
489 // NoAlloc extern "C" value caml_result_set_count(value result){
490 //   results r;
491 //   r = *( (results *) result);
492 //   return (Val_int(countResult(r)));
493 // }
494
495 NoAlloc extern "C"  value caml_xml_tree_print(value tree,value node,value fd){
496   CAMLparam3(tree,node,fd);
497   XMLTREE(tree)->Print(Int_val(fd),TREENODEVAL(node), false);
498   CAMLreturn(Val_unit);
499 }
500
501 NoAlloc extern "C"  value caml_xml_tree_flush(value tree, value fd){
502   CAMLparam2(tree,fd);
503   XMLTREE(tree)->Flush(Int_val(fd));
504   CAMLreturn(Val_unit);
505 }
506
507 // NoAlloc extern "C" value caml_set_tag_bits(value result, value tag, value tree, value node)
508 // {
509 //   results r;
510 //   XMLTree *t = XMLTREE(Field(tree,0));
511 //   treeNode opening = TREENODEVAL(node);
512 //   treeNode closing = t->Closing(opening);
513 //   TagType target_tag = Int_val(tag);
514 //   treeNode first = t->TaggedDescendant(opening,target_tag);
515 //   r = *( (results *) result);
516 //   opening = first;
517 //   while (opening != NULLT){
518 //     setResult(r,opening);
519 //     opening = t->TaggedFollowingBefore(opening,target_tag,closing);
520 //   };
521 //   return(Val_int(first));
522 // }
523
524
525 NoAlloc extern "C" value caml_bit_vector_create(value size){
526   return (value) (new vector<bool>(Int_val(size),false));
527 }
528
529 NoAlloc extern "C" value caml_bit_vector_free(value vect){
530   delete ((vector<bool>*) vect);
531   return Val_unit;
532 }
533
534 NoAlloc extern "C" value caml_bit_vector_get(value vect,value idx){
535   return Val_bool (((vector<bool>*)vect)->at(Int_val(idx)));
536 }
537
538 NoAlloc extern "C" value caml_bit_vector_set(value vect,value idx,value b){
539   (((vector<bool>*)vect)->at(Int_val(idx))) = (bool) Bool_val(b);
540   return Val_unit;
541 }
542
543 NoAlloc extern "C" value caml_bit_vector_next(value vect,value idx){
544   vector<bool>* bv = (vector<bool>*) vect;
545   int i = Int_val(idx);
546   int l = bv->size();
547   while (i < l && !((*bv)[i]))
548     i++;
549   return Val_int(i);
550 }
551 NoAlloc extern "C" value caml_bit_vector_prev(value vect,value idx){
552   int i = Int_val(idx);
553   while (i >= 0 && !((*((vector<bool>*) vect))[i]))
554     i--;
555   return Val_int(i);
556 }
557
558 extern "C" value caml_bit_vector_node_array(value vect){
559   CAMLparam0();
560   CAMLlocal1(res);
561   vector<bool>* bv = (vector<bool>*) vect;
562   vector<treeNode> vr;
563   int l = bv->size();
564   int i = 0;
565   while (i < l){
566     if ((*bv)[i]) vr.push_back(i);
567     i++;
568   };
569   l = vr.size();
570   res = caml_alloc_tuple(l);
571   for(i=0;i<l;i++)
572     caml_initialize(&Field(res,i),Val_int(vr[i]));
573   CAMLreturn (res);
574 }
575
576
577 int iterjump(XMLTree* tree, treeNode node, TagType tag, treeNode anc){
578   if (node == NULLT)
579     return 0;
580   else {
581     return
582       1
583       + iterjump(tree,tree->TaggedDescendant(node,tag),tag,node)
584       + iterjump(tree,tree->TaggedFollowingBelow(node,tag,anc),tag,anc);
585   };
586 }
587
588 extern "C" value caml_benchmark_jump(value tree,value tag){
589   int count;
590   treeNode root = XMLTREE(tree)->FirstChild(0);
591   root = XMLTREE(tree)->FirstChild(root);
592   count = iterjump(XMLTREE(tree), root , Int_val(tag),0);
593   return Val_int(count);
594 }
595
596 int iterfcns(XMLTree* tree, treeNode node){
597   if (node == NULLT)
598     return 0;
599   else {
600     int tmp = 1;
601     tmp += iterfcns(tree,tree->FirstChild(node));
602     tmp += iterfcns(tree,tree->NextSibling(node));
603
604     return tmp;
605   };
606 }
607
608 int iterfene(XMLTree* tree, treeNode node){
609   if (node == NULLT)
610     return 0;
611   else {
612     int tmp = 1;
613     tmp += iterfene(tree,tree->FirstElement(node));
614     tmp += iterfene(tree,tree->NextElement(node));
615     return tmp;
616
617   };
618 }
619
620 extern "C" value caml_benchmark_fcns(value tree){
621   int i = iterfcns(XMLTREE(tree),0);
622   return Val_int(i);
623 }
624
625 extern "C" value caml_benchmark_fene(value tree){
626   int i = iterfene(XMLTREE(tree),0);
627   return Val_int(i);
628 }
629
630 int iterlcps(XMLTree* tree, treeNode node){
631   if (node == NULLT)
632     return 0;
633   else {
634     int x = tree->Tag(node);
635     x += iterlcps(tree,tree->LastChild(node));
636     x += iterlcps(tree,tree->PrevSibling(node));
637     return x;
638   };
639 }
640
641 int fulliterative(XMLTree* tree){
642   treeNode current = tree->Root();
643   treeNode next = NULLT;
644   int count = 1; //the root
645
646   do {
647
648     while ((next = tree->FirstChild(current)) != NULLT) {
649       current = next;
650       count++;
651     };
652
653     while ( (next = tree->NextSibling(current)) == NULLT){
654       current = tree->Parent(current);
655       if (current == NULLT) return count;
656     }
657     current = next;
658     count++;
659   } while (true);
660
661 }
662
663 extern "C" value caml_benchmark_iter(value tree){
664   return Val_int(fulliterative(XMLTREE(tree)));
665 }
666
667 extern "C" value caml_benchmark_lcps(value tree){
668
669   iterlcps(XMLTREE(tree),0);
670   return Val_unit;
671
672 }
673
674 extern "C" {
675
676   typedef struct dummy_node_ {
677     struct dummy_node_* first;
678     struct dummy_node_* next;
679   } dummy_node;
680
681
682   dummy_node * new_dummy_node () {
683
684     dummy_node * node = (dummy_node*) malloc(sizeof(dummy_node));
685     if (!node)
686       printf("%s","Cannot allocate memory\n");
687
688     return node;
689   }
690
691   void free_tree(dummy_node * node){
692     if (node){
693       free_tree(node->first);
694       free_tree(node->next);
695       free(node);
696     };
697     return;
698   }
699
700   dummy_node * create_tree(XMLTree* tree, treeNode i, int mode){
701     if (i == NULLT)
702        return NULL;
703     else {
704       dummy_node * f, *n, *r;
705       //mode = i % 3;
706       r = NULL;
707       if (mode == 0) r = new_dummy_node();
708       f = create_tree(tree,tree->FirstChild(i), mode);
709       if (mode == 1) r = new_dummy_node();
710       n = create_tree(tree,tree->NextSibling(i), mode);
711       if (mode == 2) r = new_dummy_node();
712       r->first = f;
713       r->next = n;
714       return r;
715     };
716   }
717
718   int iter_tree(dummy_node * n){
719     if (n == NULL)
720       return 0;
721     else
722       return 1 + iter_tree (n->first) + iter_tree (n->next);
723   }
724 }
725 extern "C" value caml_build_pointers(value tree, value mode){
726   return ((value) create_tree(XMLTREE(Field(tree,0)),0, Int_val(mode)));
727 }
728
729 extern "C" value caml_iter_pointers (value node){
730   return Val_int(iter_tree((dummy_node*) node));
731
732 }
733
734 extern "C" value caml_free_pointers(value node){
735   free_tree((dummy_node*) node);
736   return Val_unit;
737 }
738 /**
739  *  Interface to the TextCollection
740  */
741
742 /**
743  *  Utility functions
744  */
745
746 extern "C"  value caml_text_collection_get_text(value tree, value id){
747   CAMLparam2(tree,id);
748   CAMLlocal1(str);
749   uchar* txt = XMLTREE(tree)->GetText((DocID) Int_val(id));
750   str = caml_copy_string((const char*)txt);
751   CAMLreturn (str);
752 }
753
754
755 extern "C"  value caml_text_collection_empty_text(value tree,value id){
756   CAMLparam2(tree,id);
757   CAMLreturn ( Val_int((XMLTREE(tree))->EmptyText((DocID) Int_val(id))));
758 }
759
760 bool docId_comp(DocID x, DocID y) { return x < y; };
761
762 /**
763  * Existential queries
764  */
765
766 extern "C"  value caml_text_collection_is_prefix(value tree,value str){
767   CAMLparam2(tree,str);
768   uchar * cstr = (uchar *) String_val(str);
769   CAMLreturn (Val_bool((int) XMLTREE(tree)->IsPrefix(cstr)));
770 }
771
772 extern "C"  value caml_text_collection_is_suffix(value tree,value str){
773   CAMLparam2(tree,str);
774   uchar * cstr = (uchar *) String_val(str);
775   CAMLreturn (Val_bool((int) XMLTREE(tree)->IsSuffix(cstr)));
776 }
777 extern "C"  value caml_text_collection_is_equal(value tree,value str){
778   CAMLparam2(tree,str);
779   uchar * cstr = (uchar *) String_val(str);
780   CAMLreturn (Val_bool((int) XMLTREE(tree)->IsEqual(cstr)));
781 }
782 extern "C"  value caml_text_collection_is_contains(value tree,value str){
783   CAMLparam2(tree,str);
784   uchar * cstr = (uchar *) String_val(str);
785   CAMLreturn ( Val_bool((int) XMLTREE(tree)->IsContains(cstr)));
786 }
787
788 extern "C"  value caml_text_collection_is_lessthan(value tree,value str){
789   CAMLparam2(tree,str);
790   uchar * cstr = (uchar *) String_val(str);
791   CAMLreturn ( Val_bool((int) XMLTREE(tree)->IsLessThan(cstr)));
792 }
793
794
795 /**
796  * Count Queries
797  */
798
799 /**
800  *  Global counting
801  */
802 extern "C"  value caml_text_collection_count(value tree,value str){
803   CAMLparam2(tree,str);
804   uchar * cstr = (uchar *) String_val(str);
805   CAMLreturn (Val_int((XMLTREE(tree)->Count(cstr))));
806 }
807
808 extern "C"  value caml_text_collection_count_prefix(value tree,value str){
809   CAMLparam2(tree,str);
810   uchar * cstr = (uchar *) String_val(str);
811   CAMLreturn (Val_int((XMLTREE(tree)->CountPrefix(cstr))));
812 }
813
814 extern "C"  value caml_text_collection_count_suffix(value tree,value str){
815   CAMLparam2(tree,str);
816   uchar * cstr = (uchar *) String_val(str);
817   CAMLreturn (Val_int((XMLTREE(tree)->CountSuffix(cstr))));
818 }
819
820 extern "C"  value caml_text_collection_count_equal(value tree,value str){
821   CAMLparam2(tree,str);
822   uchar * cstr = (uchar *) String_val(str);
823   CAMLreturn (Val_int((XMLTREE(tree)->CountEqual(cstr))));
824 }
825
826 extern "C"  value caml_text_collection_count_contains(value tree,value str){
827   CAMLparam2(tree,str);
828   uchar * cstr = (uchar *) String_val(str);
829   CAMLreturn (Val_int((XMLTREE(tree)->CountContains(cstr))));
830 }
831
832 extern "C"  value caml_text_collection_count_lessthan(value tree,value str){
833   CAMLparam2(tree,str);
834   uchar * cstr = (uchar *) String_val(str);
835   CAMLreturn (Val_int((XMLTREE(tree)->CountLessThan(cstr))));
836 }
837
838 static value sort_alloc_array(std::vector<DocID> results, value resarray){
839   std::sort(results.begin(), results.end(), docId_comp);
840     size_t s = results.size();
841     resarray = caml_alloc_tuple(s);
842     for (size_t i = 0; i < s ;i++){
843       caml_initialize(&Field(resarray,i),Val_int(results[i]));
844     };
845     return resarray;
846
847 }
848
849 /**
850  * Full reporting queries
851  */
852
853 extern "C"  value caml_text_collection_prefix(value tree,value str){
854   CAMLparam2(tree,str);
855   CAMLlocal1(resarray);
856   uchar * cstr = (uchar *) String_val(str);
857   std::vector<DocID> results = XMLTREE(tree)->Prefix(cstr);
858   CAMLreturn (sort_alloc_array(results,resarray));
859 }
860
861 extern "C"  value caml_text_collection_suffix(value tree,value str){
862   CAMLparam2(tree,str);
863   CAMLlocal1(resarray);
864   uchar * cstr = (uchar *) String_val(str);
865   std::vector<DocID> results = XMLTREE(tree)->Suffix(cstr);
866   CAMLreturn (sort_alloc_array(results,resarray));
867 }
868
869 extern "C"  value caml_text_collection_equals(value tree,value str){
870   CAMLparam2(tree,str);
871   CAMLlocal1(resarray);
872   uchar * cstr = (uchar *) strdup(String_val(str));
873   std::vector<DocID> results = XMLTREE(tree)->Equals(cstr);
874   free(cstr);
875   CAMLreturn (sort_alloc_array(results,resarray));
876 }
877
878 extern "C"  value caml_text_collection_contains(value tree,value str){
879   CAMLparam2(tree,str);
880   CAMLlocal1(resarray);
881   uchar * cstr = (uchar *) String_val(str);
882   std::vector<DocID> results = XMLTREE(tree)->Contains(cstr);
883   CAMLreturn (sort_alloc_array(results,resarray));
884 }
885
886 extern "C"  value caml_text_collection_lessthan(value tree,value str){
887   CAMLparam2(tree,str);
888   CAMLlocal1(resarray);
889   uchar * cstr = (uchar *) String_val(str);
890   std::vector<DocID> results = XMLTREE(tree)->LessThan(cstr);
891   CAMLreturn (sort_alloc_array(results,resarray));
892 }
893
894 /** Full reporting into a bit vector
895  */
896
897 #define BV_QUERY(pref, Pref) \
898   extern "C" value caml_text_collection_## pref ##_bv(value tree, value str){ \
899   CAMLparam2(tree, str);                                                \
900   CAMLlocal3(res, res_bv, res_array);                                   \
901   int j;                                                                \
902   uchar * cstr = (uchar *) strdup(String_val(str));                     \
903   std::vector<DocID> results = XMLTREE(tree)->Pref(cstr);               \
904   res_bv = caml_alloc_string((XMLTREE(tree)->Size() / 4) + 2);          \
905   unsigned long slen = caml_string_length(res_bv);                      \
906   memset(&(Byte(res_bv,0)), 0, slen);                                   \
907   res_array = caml_alloc_shr(results.size(), 0);                        \
908   for (unsigned int i = 0; i < results.size(); ++i) {                   \
909     j = XMLTREE(tree)->ParentNode(results[i]);                          \
910     Byte(res_bv, j >> 3) |=   (1 << (j & 7));                           \
911     caml_initialize(&Field(res_array, i), Val_int(j));                  \
912   };                                                                    \
913   free(cstr);                                                           \
914   res = caml_alloc(2, 0);                                               \
915   Store_field(res, 0, res_bv);                                          \
916   Store_field(res, 1, res_array);                                       \
917   CAMLreturn(res);                                                      \
918   }                                                                     \
919
920
921 BV_QUERY(prefix, Prefix)
922 BV_QUERY(suffix, Suffix)
923 BV_QUERY(equals, Equals)
924 BV_QUERY(contains, Contains)
925 BV_QUERY(lessthan, LessThan)