xref: /reactos/sdk/lib/3rdparty/libxml2/xpointer.c (revision c7bba39a)
1 /*
2  * xpointer.c : Code to handle XML Pointer
3  *
4  * Base implementation was made accordingly to
5  * W3C Candidate Recommendation 7 June 2000
6  * http://www.w3.org/TR/2000/CR-xptr-20000607
7  *
8  * Added support for the element() scheme described in:
9  * W3C Proposed Recommendation 13 November 2002
10  * http://www.w3.org/TR/2002/PR-xptr-element-20021113/
11  *
12  * See Copyright for the status of this software.
13  *
14  * daniel@veillard.com
15  */
16 
17 /* To avoid EBCDIC trouble when parsing on zOS */
18 #if defined(__MVS__)
19 #pragma convert("ISO8859-1")
20 #endif
21 
22 #define IN_LIBXML
23 #include "libxml.h"
24 
25 /*
26  * TODO: better handling of error cases, the full expression should
27  *       be parsed beforehand instead of a progressive evaluation
28  * TODO: Access into entities references are not supported now ...
29  *       need a start to be able to pop out of entities refs since
30  *       parent is the endity declaration, not the ref.
31  */
32 
33 #include <string.h>
34 #include <libxml/xpointer.h>
35 #include <libxml/xmlmemory.h>
36 #include <libxml/parserInternals.h>
37 #include <libxml/uri.h>
38 #include <libxml/xpath.h>
39 #include <libxml/xpathInternals.h>
40 #include <libxml/xmlerror.h>
41 #include <libxml/globals.h>
42 
43 #ifdef LIBXML_XPTR_ENABLED
44 
45 /* Add support of the xmlns() xpointer scheme to initialize the namespaces */
46 #define XPTR_XMLNS_SCHEME
47 
48 /* #define DEBUG_RANGES */
49 #ifdef DEBUG_RANGES
50 #ifdef LIBXML_DEBUG_ENABLED
51 #include <libxml/debugXML.h>
52 #endif
53 #endif
54 
55 #define TODO								\
56     xmlGenericError(xmlGenericErrorContext,				\
57 	    "Unimplemented block at %s:%d\n",				\
58             __FILE__, __LINE__);
59 
60 #define STRANGE							\
61     xmlGenericError(xmlGenericErrorContext,				\
62 	    "Internal error at %s:%d\n",				\
63             __FILE__, __LINE__);
64 
65 /************************************************************************
66  *									*
67  *		Some factorized error routines				*
68  *									*
69  ************************************************************************/
70 
71 /**
72  * xmlXPtrErrMemory:
73  * @extra:  extra informations
74  *
75  * Handle a redefinition of attribute error
76  */
77 static void
78 xmlXPtrErrMemory(const char *extra)
79 {
80     __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_XPOINTER,
81 		    XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0, extra,
82 		    NULL, NULL, 0, 0,
83 		    "Memory allocation failed : %s\n", extra);
84 }
85 
86 /**
87  * xmlXPtrErr:
88  * @ctxt:  an XPTR evaluation context
89  * @extra:  extra informations
90  *
91  * Handle a redefinition of attribute error
92  */
93 static void LIBXML_ATTR_FORMAT(3,0)
94 xmlXPtrErr(xmlXPathParserContextPtr ctxt, int error,
95            const char * msg, const xmlChar *extra)
96 {
97     if (ctxt != NULL)
98         ctxt->error = error;
99     if ((ctxt == NULL) || (ctxt->context == NULL)) {
100 	__xmlRaiseError(NULL, NULL, NULL,
101 			NULL, NULL, XML_FROM_XPOINTER, error,
102 			XML_ERR_ERROR, NULL, 0,
103 			(const char *) extra, NULL, NULL, 0, 0,
104 			msg, extra);
105 	return;
106     }
107 
108     /* cleanup current last error */
109     xmlResetError(&ctxt->context->lastError);
110 
111     ctxt->context->lastError.domain = XML_FROM_XPOINTER;
112     ctxt->context->lastError.code = error;
113     ctxt->context->lastError.level = XML_ERR_ERROR;
114     ctxt->context->lastError.str1 = (char *) xmlStrdup(ctxt->base);
115     ctxt->context->lastError.int1 = ctxt->cur - ctxt->base;
116     ctxt->context->lastError.node = ctxt->context->debugNode;
117     if (ctxt->context->error != NULL) {
118 	ctxt->context->error(ctxt->context->userData,
119 	                     &ctxt->context->lastError);
120     } else {
121 	__xmlRaiseError(NULL, NULL, NULL,
122 			NULL, ctxt->context->debugNode, XML_FROM_XPOINTER,
123 			error, XML_ERR_ERROR, NULL, 0,
124 			(const char *) extra, (const char *) ctxt->base, NULL,
125 			ctxt->cur - ctxt->base, 0,
126 			msg, extra);
127     }
128 }
129 
130 /************************************************************************
131  *									*
132  *		A few helper functions for child sequences		*
133  *									*
134  ************************************************************************/
135 /* xmlXPtrAdvanceNode is a private function, but used by xinclude.c */
136 xmlNodePtr xmlXPtrAdvanceNode(xmlNodePtr cur, int *level);
137 /**
138  * xmlXPtrGetArity:
139  * @cur:  the node
140  *
141  * Returns the number of child for an element, -1 in case of error
142  */
143 static int
144 xmlXPtrGetArity(xmlNodePtr cur) {
145     int i;
146     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
147 	return(-1);
148     cur = cur->children;
149     for (i = 0;cur != NULL;cur = cur->next) {
150 	if ((cur->type == XML_ELEMENT_NODE) ||
151 	    (cur->type == XML_DOCUMENT_NODE) ||
152 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
153 	    i++;
154 	}
155     }
156     return(i);
157 }
158 
159 /**
160  * xmlXPtrGetIndex:
161  * @cur:  the node
162  *
163  * Returns the index of the node in its parent children list, -1
164  *         in case of error
165  */
166 static int
167 xmlXPtrGetIndex(xmlNodePtr cur) {
168     int i;
169     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
170 	return(-1);
171     for (i = 1;cur != NULL;cur = cur->prev) {
172 	if ((cur->type == XML_ELEMENT_NODE) ||
173 	    (cur->type == XML_DOCUMENT_NODE) ||
174 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
175 	    i++;
176 	}
177     }
178     return(i);
179 }
180 
181 /**
182  * xmlXPtrGetNthChild:
183  * @cur:  the node
184  * @no:  the child number
185  *
186  * Returns the @no'th element child of @cur or NULL
187  */
188 static xmlNodePtr
189 xmlXPtrGetNthChild(xmlNodePtr cur, int no) {
190     int i;
191     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
192 	return(cur);
193     cur = cur->children;
194     for (i = 0;i <= no;cur = cur->next) {
195 	if (cur == NULL)
196 	    return(cur);
197 	if ((cur->type == XML_ELEMENT_NODE) ||
198 	    (cur->type == XML_DOCUMENT_NODE) ||
199 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
200 	    i++;
201 	    if (i == no)
202 		break;
203 	}
204     }
205     return(cur);
206 }
207 
208 /************************************************************************
209  *									*
210  *		Handling of XPointer specific types			*
211  *									*
212  ************************************************************************/
213 
214 /**
215  * xmlXPtrCmpPoints:
216  * @node1:  the first node
217  * @index1:  the first index
218  * @node2:  the second node
219  * @index2:  the second index
220  *
221  * Compare two points w.r.t document order
222  *
223  * Returns -2 in case of error 1 if first point < second point, 0 if
224  *         that's the same point, -1 otherwise
225  */
226 static int
227 xmlXPtrCmpPoints(xmlNodePtr node1, int index1, xmlNodePtr node2, int index2) {
228     if ((node1 == NULL) || (node2 == NULL))
229 	return(-2);
230     /*
231      * a couple of optimizations which will avoid computations in most cases
232      */
233     if (node1 == node2) {
234 	if (index1 < index2)
235 	    return(1);
236 	if (index1 > index2)
237 	    return(-1);
238 	return(0);
239     }
240     return(xmlXPathCmpNodes(node1, node2));
241 }
242 
243 /**
244  * xmlXPtrNewPoint:
245  * @node:  the xmlNodePtr
246  * @indx:  the indx within the node
247  *
248  * Create a new xmlXPathObjectPtr of type point
249  *
250  * Returns the newly created object.
251  */
252 static xmlXPathObjectPtr
253 xmlXPtrNewPoint(xmlNodePtr node, int indx) {
254     xmlXPathObjectPtr ret;
255 
256     if (node == NULL)
257 	return(NULL);
258     if (indx < 0)
259 	return(NULL);
260 
261     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
262     if (ret == NULL) {
263         xmlXPtrErrMemory("allocating point");
264 	return(NULL);
265     }
266     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
267     ret->type = XPATH_POINT;
268     ret->user = (void *) node;
269     ret->index = indx;
270     return(ret);
271 }
272 
273 /**
274  * xmlXPtrRangeCheckOrder:
275  * @range:  an object range
276  *
277  * Make sure the points in the range are in the right order
278  */
279 static void
280 xmlXPtrRangeCheckOrder(xmlXPathObjectPtr range) {
281     int tmp;
282     xmlNodePtr tmp2;
283     if (range == NULL)
284 	return;
285     if (range->type != XPATH_RANGE)
286 	return;
287     if (range->user2 == NULL)
288 	return;
289     tmp = xmlXPtrCmpPoints(range->user, range->index,
290 	                     range->user2, range->index2);
291     if (tmp == -1) {
292 	tmp2 = range->user;
293 	range->user = range->user2;
294 	range->user2 = tmp2;
295 	tmp = range->index;
296 	range->index = range->index2;
297 	range->index2 = tmp;
298     }
299 }
300 
301 /**
302  * xmlXPtrRangesEqual:
303  * @range1:  the first range
304  * @range2:  the second range
305  *
306  * Compare two ranges
307  *
308  * Returns 1 if equal, 0 otherwise
309  */
310 static int
311 xmlXPtrRangesEqual(xmlXPathObjectPtr range1, xmlXPathObjectPtr range2) {
312     if (range1 == range2)
313 	return(1);
314     if ((range1 == NULL) || (range2 == NULL))
315 	return(0);
316     if (range1->type != range2->type)
317 	return(0);
318     if (range1->type != XPATH_RANGE)
319 	return(0);
320     if (range1->user != range2->user)
321 	return(0);
322     if (range1->index != range2->index)
323 	return(0);
324     if (range1->user2 != range2->user2)
325 	return(0);
326     if (range1->index2 != range2->index2)
327 	return(0);
328     return(1);
329 }
330 
331 /**
332  * xmlXPtrNewRangeInternal:
333  * @start:  the starting node
334  * @startindex:  the start index
335  * @end:  the ending point
336  * @endindex:  the ending index
337  *
338  * Internal function to create a new xmlXPathObjectPtr of type range
339  *
340  * Returns the newly created object.
341  */
342 static xmlXPathObjectPtr
343 xmlXPtrNewRangeInternal(xmlNodePtr start, int startindex,
344                         xmlNodePtr end, int endindex) {
345     xmlXPathObjectPtr ret;
346 
347     /*
348      * Namespace nodes must be copied (see xmlXPathNodeSetDupNs).
349      * Disallow them for now.
350      */
351     if ((start != NULL) && (start->type == XML_NAMESPACE_DECL))
352 	return(NULL);
353     if ((end != NULL) && (end->type == XML_NAMESPACE_DECL))
354 	return(NULL);
355 
356     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
357     if (ret == NULL) {
358         xmlXPtrErrMemory("allocating range");
359 	return(NULL);
360     }
361     memset(ret, 0, sizeof(xmlXPathObject));
362     ret->type = XPATH_RANGE;
363     ret->user = start;
364     ret->index = startindex;
365     ret->user2 = end;
366     ret->index2 = endindex;
367     return(ret);
368 }
369 
370 /**
371  * xmlXPtrNewRange:
372  * @start:  the starting node
373  * @startindex:  the start index
374  * @end:  the ending point
375  * @endindex:  the ending index
376  *
377  * Create a new xmlXPathObjectPtr of type range
378  *
379  * Returns the newly created object.
380  */
381 xmlXPathObjectPtr
382 xmlXPtrNewRange(xmlNodePtr start, int startindex,
383 	        xmlNodePtr end, int endindex) {
384     xmlXPathObjectPtr ret;
385 
386     if (start == NULL)
387 	return(NULL);
388     if (end == NULL)
389 	return(NULL);
390     if (startindex < 0)
391 	return(NULL);
392     if (endindex < 0)
393 	return(NULL);
394 
395     ret = xmlXPtrNewRangeInternal(start, startindex, end, endindex);
396     xmlXPtrRangeCheckOrder(ret);
397     return(ret);
398 }
399 
400 /**
401  * xmlXPtrNewRangePoints:
402  * @start:  the starting point
403  * @end:  the ending point
404  *
405  * Create a new xmlXPathObjectPtr of type range using 2 Points
406  *
407  * Returns the newly created object.
408  */
409 xmlXPathObjectPtr
410 xmlXPtrNewRangePoints(xmlXPathObjectPtr start, xmlXPathObjectPtr end) {
411     xmlXPathObjectPtr ret;
412 
413     if (start == NULL)
414 	return(NULL);
415     if (end == NULL)
416 	return(NULL);
417     if (start->type != XPATH_POINT)
418 	return(NULL);
419     if (end->type != XPATH_POINT)
420 	return(NULL);
421 
422     ret = xmlXPtrNewRangeInternal(start->user, start->index, end->user,
423                                   end->index);
424     xmlXPtrRangeCheckOrder(ret);
425     return(ret);
426 }
427 
428 /**
429  * xmlXPtrNewRangePointNode:
430  * @start:  the starting point
431  * @end:  the ending node
432  *
433  * Create a new xmlXPathObjectPtr of type range from a point to a node
434  *
435  * Returns the newly created object.
436  */
437 xmlXPathObjectPtr
438 xmlXPtrNewRangePointNode(xmlXPathObjectPtr start, xmlNodePtr end) {
439     xmlXPathObjectPtr ret;
440 
441     if (start == NULL)
442 	return(NULL);
443     if (end == NULL)
444 	return(NULL);
445     if (start->type != XPATH_POINT)
446 	return(NULL);
447 
448     ret = xmlXPtrNewRangeInternal(start->user, start->index, end, -1);
449     xmlXPtrRangeCheckOrder(ret);
450     return(ret);
451 }
452 
453 /**
454  * xmlXPtrNewRangeNodePoint:
455  * @start:  the starting node
456  * @end:  the ending point
457  *
458  * Create a new xmlXPathObjectPtr of type range from a node to a point
459  *
460  * Returns the newly created object.
461  */
462 xmlXPathObjectPtr
463 xmlXPtrNewRangeNodePoint(xmlNodePtr start, xmlXPathObjectPtr end) {
464     xmlXPathObjectPtr ret;
465 
466     if (start == NULL)
467 	return(NULL);
468     if (end == NULL)
469 	return(NULL);
470     if (start->type != XPATH_POINT)
471 	return(NULL);
472     if (end->type != XPATH_POINT)
473 	return(NULL);
474 
475     ret = xmlXPtrNewRangeInternal(start, -1, end->user, end->index);
476     xmlXPtrRangeCheckOrder(ret);
477     return(ret);
478 }
479 
480 /**
481  * xmlXPtrNewRangeNodes:
482  * @start:  the starting node
483  * @end:  the ending node
484  *
485  * Create a new xmlXPathObjectPtr of type range using 2 nodes
486  *
487  * Returns the newly created object.
488  */
489 xmlXPathObjectPtr
490 xmlXPtrNewRangeNodes(xmlNodePtr start, xmlNodePtr end) {
491     xmlXPathObjectPtr ret;
492 
493     if (start == NULL)
494 	return(NULL);
495     if (end == NULL)
496 	return(NULL);
497 
498     ret = xmlXPtrNewRangeInternal(start, -1, end, -1);
499     xmlXPtrRangeCheckOrder(ret);
500     return(ret);
501 }
502 
503 /**
504  * xmlXPtrNewCollapsedRange:
505  * @start:  the starting and ending node
506  *
507  * Create a new xmlXPathObjectPtr of type range using a single nodes
508  *
509  * Returns the newly created object.
510  */
511 xmlXPathObjectPtr
512 xmlXPtrNewCollapsedRange(xmlNodePtr start) {
513     xmlXPathObjectPtr ret;
514 
515     if (start == NULL)
516 	return(NULL);
517 
518     ret = xmlXPtrNewRangeInternal(start, -1, NULL, -1);
519     return(ret);
520 }
521 
522 /**
523  * xmlXPtrNewRangeNodeObject:
524  * @start:  the starting node
525  * @end:  the ending object
526  *
527  * Create a new xmlXPathObjectPtr of type range from a not to an object
528  *
529  * Returns the newly created object.
530  */
531 xmlXPathObjectPtr
532 xmlXPtrNewRangeNodeObject(xmlNodePtr start, xmlXPathObjectPtr end) {
533     xmlNodePtr endNode;
534     int endIndex;
535     xmlXPathObjectPtr ret;
536 
537     if (start == NULL)
538 	return(NULL);
539     if (end == NULL)
540 	return(NULL);
541     switch (end->type) {
542 	case XPATH_POINT:
543 	    endNode = end->user;
544 	    endIndex = end->index;
545 	    break;
546 	case XPATH_RANGE:
547 	    endNode = end->user2;
548 	    endIndex = end->index2;
549 	    break;
550 	case XPATH_NODESET:
551 	    /*
552 	     * Empty set ...
553 	     */
554 	    if ((end->nodesetval == NULL) || (end->nodesetval->nodeNr <= 0))
555 		return(NULL);
556 	    endNode = end->nodesetval->nodeTab[end->nodesetval->nodeNr - 1];
557 	    endIndex = -1;
558 	    break;
559 	default:
560 	    /* TODO */
561 	    return(NULL);
562     }
563 
564     ret = xmlXPtrNewRangeInternal(start, -1, endNode, endIndex);
565     xmlXPtrRangeCheckOrder(ret);
566     return(ret);
567 }
568 
569 #define XML_RANGESET_DEFAULT	10
570 
571 /**
572  * xmlXPtrLocationSetCreate:
573  * @val:  an initial xmlXPathObjectPtr, or NULL
574  *
575  * Create a new xmlLocationSetPtr of type double and of value @val
576  *
577  * Returns the newly created object.
578  */
579 xmlLocationSetPtr
580 xmlXPtrLocationSetCreate(xmlXPathObjectPtr val) {
581     xmlLocationSetPtr ret;
582 
583     ret = (xmlLocationSetPtr) xmlMalloc(sizeof(xmlLocationSet));
584     if (ret == NULL) {
585         xmlXPtrErrMemory("allocating locationset");
586 	return(NULL);
587     }
588     memset(ret, 0 , (size_t) sizeof(xmlLocationSet));
589     if (val != NULL) {
590         ret->locTab = (xmlXPathObjectPtr *) xmlMalloc(XML_RANGESET_DEFAULT *
591 					     sizeof(xmlXPathObjectPtr));
592 	if (ret->locTab == NULL) {
593 	    xmlXPtrErrMemory("allocating locationset");
594 	    xmlFree(ret);
595 	    return(NULL);
596 	}
597 	memset(ret->locTab, 0 ,
598 	       XML_RANGESET_DEFAULT * (size_t) sizeof(xmlXPathObjectPtr));
599         ret->locMax = XML_RANGESET_DEFAULT;
600 	ret->locTab[ret->locNr++] = val;
601     }
602     return(ret);
603 }
604 
605 /**
606  * xmlXPtrLocationSetAdd:
607  * @cur:  the initial range set
608  * @val:  a new xmlXPathObjectPtr
609  *
610  * add a new xmlXPathObjectPtr to an existing LocationSet
611  * If the location already exist in the set @val is freed.
612  */
613 void
614 xmlXPtrLocationSetAdd(xmlLocationSetPtr cur, xmlXPathObjectPtr val) {
615     int i;
616 
617     if ((cur == NULL) || (val == NULL)) return;
618 
619     /*
620      * check against doublons
621      */
622     for (i = 0;i < cur->locNr;i++) {
623 	if (xmlXPtrRangesEqual(cur->locTab[i], val)) {
624 	    xmlXPathFreeObject(val);
625 	    return;
626 	}
627     }
628 
629     /*
630      * grow the locTab if needed
631      */
632     if (cur->locMax == 0) {
633         cur->locTab = (xmlXPathObjectPtr *) xmlMalloc(XML_RANGESET_DEFAULT *
634 					     sizeof(xmlXPathObjectPtr));
635 	if (cur->locTab == NULL) {
636 	    xmlXPtrErrMemory("adding location to set");
637 	    return;
638 	}
639 	memset(cur->locTab, 0 ,
640 	       XML_RANGESET_DEFAULT * (size_t) sizeof(xmlXPathObjectPtr));
641         cur->locMax = XML_RANGESET_DEFAULT;
642     } else if (cur->locNr == cur->locMax) {
643         xmlXPathObjectPtr *temp;
644 
645         cur->locMax *= 2;
646 	temp = (xmlXPathObjectPtr *) xmlRealloc(cur->locTab, cur->locMax *
647 				      sizeof(xmlXPathObjectPtr));
648 	if (temp == NULL) {
649 	    xmlXPtrErrMemory("adding location to set");
650 	    return;
651 	}
652 	cur->locTab = temp;
653     }
654     cur->locTab[cur->locNr++] = val;
655 }
656 
657 /**
658  * xmlXPtrLocationSetMerge:
659  * @val1:  the first LocationSet
660  * @val2:  the second LocationSet
661  *
662  * Merges two rangesets, all ranges from @val2 are added to @val1
663  *
664  * Returns val1 once extended or NULL in case of error.
665  */
666 xmlLocationSetPtr
667 xmlXPtrLocationSetMerge(xmlLocationSetPtr val1, xmlLocationSetPtr val2) {
668     int i;
669 
670     if (val1 == NULL) return(NULL);
671     if (val2 == NULL) return(val1);
672 
673     /*
674      * !!!!! this can be optimized a lot, knowing that both
675      *       val1 and val2 already have unicity of their values.
676      */
677 
678     for (i = 0;i < val2->locNr;i++)
679         xmlXPtrLocationSetAdd(val1, val2->locTab[i]);
680 
681     return(val1);
682 }
683 
684 /**
685  * xmlXPtrLocationSetDel:
686  * @cur:  the initial range set
687  * @val:  an xmlXPathObjectPtr
688  *
689  * Removes an xmlXPathObjectPtr from an existing LocationSet
690  */
691 void
692 xmlXPtrLocationSetDel(xmlLocationSetPtr cur, xmlXPathObjectPtr val) {
693     int i;
694 
695     if (cur == NULL) return;
696     if (val == NULL) return;
697 
698     /*
699      * check against doublons
700      */
701     for (i = 0;i < cur->locNr;i++)
702         if (cur->locTab[i] == val) break;
703 
704     if (i >= cur->locNr) {
705 #ifdef DEBUG
706         xmlGenericError(xmlGenericErrorContext,
707 	        "xmlXPtrLocationSetDel: Range wasn't found in RangeList\n");
708 #endif
709         return;
710     }
711     cur->locNr--;
712     for (;i < cur->locNr;i++)
713         cur->locTab[i] = cur->locTab[i + 1];
714     cur->locTab[cur->locNr] = NULL;
715 }
716 
717 /**
718  * xmlXPtrLocationSetRemove:
719  * @cur:  the initial range set
720  * @val:  the index to remove
721  *
722  * Removes an entry from an existing LocationSet list.
723  */
724 void
725 xmlXPtrLocationSetRemove(xmlLocationSetPtr cur, int val) {
726     if (cur == NULL) return;
727     if (val >= cur->locNr) return;
728     cur->locNr--;
729     for (;val < cur->locNr;val++)
730         cur->locTab[val] = cur->locTab[val + 1];
731     cur->locTab[cur->locNr] = NULL;
732 }
733 
734 /**
735  * xmlXPtrFreeLocationSet:
736  * @obj:  the xmlLocationSetPtr to free
737  *
738  * Free the LocationSet compound (not the actual ranges !).
739  */
740 void
741 xmlXPtrFreeLocationSet(xmlLocationSetPtr obj) {
742     int i;
743 
744     if (obj == NULL) return;
745     if (obj->locTab != NULL) {
746 	for (i = 0;i < obj->locNr; i++) {
747             xmlXPathFreeObject(obj->locTab[i]);
748 	}
749 	xmlFree(obj->locTab);
750     }
751     xmlFree(obj);
752 }
753 
754 /**
755  * xmlXPtrNewLocationSetNodes:
756  * @start:  the start NodePtr value
757  * @end:  the end NodePtr value or NULL
758  *
759  * Create a new xmlXPathObjectPtr of type LocationSet and initialize
760  * it with the single range made of the two nodes @start and @end
761  *
762  * Returns the newly created object.
763  */
764 xmlXPathObjectPtr
765 xmlXPtrNewLocationSetNodes(xmlNodePtr start, xmlNodePtr end) {
766     xmlXPathObjectPtr ret;
767 
768     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
769     if (ret == NULL) {
770         xmlXPtrErrMemory("allocating locationset");
771 	return(NULL);
772     }
773     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
774     ret->type = XPATH_LOCATIONSET;
775     if (end == NULL)
776 	ret->user = xmlXPtrLocationSetCreate(xmlXPtrNewCollapsedRange(start));
777     else
778 	ret->user = xmlXPtrLocationSetCreate(xmlXPtrNewRangeNodes(start,end));
779     return(ret);
780 }
781 
782 /**
783  * xmlXPtrNewLocationSetNodeSet:
784  * @set:  a node set
785  *
786  * Create a new xmlXPathObjectPtr of type LocationSet and initialize
787  * it with all the nodes from @set
788  *
789  * Returns the newly created object.
790  */
791 xmlXPathObjectPtr
792 xmlXPtrNewLocationSetNodeSet(xmlNodeSetPtr set) {
793     xmlXPathObjectPtr ret;
794 
795     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
796     if (ret == NULL) {
797         xmlXPtrErrMemory("allocating locationset");
798 	return(NULL);
799     }
800     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
801     ret->type = XPATH_LOCATIONSET;
802     if (set != NULL) {
803 	int i;
804 	xmlLocationSetPtr newset;
805 
806 	newset = xmlXPtrLocationSetCreate(NULL);
807 	if (newset == NULL)
808 	    return(ret);
809 
810 	for (i = 0;i < set->nodeNr;i++)
811 	    xmlXPtrLocationSetAdd(newset,
812 		        xmlXPtrNewCollapsedRange(set->nodeTab[i]));
813 
814 	ret->user = (void *) newset;
815     }
816     return(ret);
817 }
818 
819 /**
820  * xmlXPtrWrapLocationSet:
821  * @val:  the LocationSet value
822  *
823  * Wrap the LocationSet @val in a new xmlXPathObjectPtr
824  *
825  * Returns the newly created object.
826  */
827 xmlXPathObjectPtr
828 xmlXPtrWrapLocationSet(xmlLocationSetPtr val) {
829     xmlXPathObjectPtr ret;
830 
831     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
832     if (ret == NULL) {
833         xmlXPtrErrMemory("allocating locationset");
834 	return(NULL);
835     }
836     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
837     ret->type = XPATH_LOCATIONSET;
838     ret->user = (void *) val;
839     return(ret);
840 }
841 
842 /************************************************************************
843  *									*
844  *			The parser					*
845  *									*
846  ************************************************************************/
847 
848 static void xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt, xmlChar *name);
849 
850 /*
851  * Macros for accessing the content. Those should be used only by the parser,
852  * and not exported.
853  *
854  * Dirty macros, i.e. one need to make assumption on the context to use them
855  *
856  *   CUR_PTR return the current pointer to the xmlChar to be parsed.
857  *   CUR     returns the current xmlChar value, i.e. a 8 bit value
858  *           in ISO-Latin or UTF-8.
859  *           This should be used internally by the parser
860  *           only to compare to ASCII values otherwise it would break when
861  *           running with UTF-8 encoding.
862  *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
863  *           to compare on ASCII based substring.
864  *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
865  *           strings within the parser.
866  *   CURRENT Returns the current char value, with the full decoding of
867  *           UTF-8 if we are using this mode. It returns an int.
868  *   NEXT    Skip to the next character, this does the proper decoding
869  *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
870  *           It returns the pointer to the current xmlChar.
871  */
872 
873 #define CUR (*ctxt->cur)
874 #define SKIP(val) ctxt->cur += (val)
875 #define NXT(val) ctxt->cur[(val)]
876 #define CUR_PTR ctxt->cur
877 
878 #define SKIP_BLANKS							\
879     while (IS_BLANK_CH(*(ctxt->cur))) NEXT
880 
881 #define CURRENT (*ctxt->cur)
882 #define NEXT ((*ctxt->cur) ?  ctxt->cur++: ctxt->cur)
883 
884 /*
885  * xmlXPtrGetChildNo:
886  * @ctxt:  the XPointer Parser context
887  * @index:  the child number
888  *
889  * Move the current node of the nodeset on the stack to the
890  * given child if found
891  */
892 static void
893 xmlXPtrGetChildNo(xmlXPathParserContextPtr ctxt, int indx) {
894     xmlNodePtr cur = NULL;
895     xmlXPathObjectPtr obj;
896     xmlNodeSetPtr oldset;
897 
898     CHECK_TYPE(XPATH_NODESET);
899     obj = valuePop(ctxt);
900     oldset = obj->nodesetval;
901     if ((indx <= 0) || (oldset == NULL) || (oldset->nodeNr != 1)) {
902 	xmlXPathFreeObject(obj);
903 	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
904 	return;
905     }
906     cur = xmlXPtrGetNthChild(oldset->nodeTab[0], indx);
907     if (cur == NULL) {
908 	xmlXPathFreeObject(obj);
909 	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
910 	return;
911     }
912     oldset->nodeTab[0] = cur;
913     valuePush(ctxt, obj);
914 }
915 
916 /**
917  * xmlXPtrEvalXPtrPart:
918  * @ctxt:  the XPointer Parser context
919  * @name:  the preparsed Scheme for the XPtrPart
920  *
921  * XPtrPart ::= 'xpointer' '(' XPtrExpr ')'
922  *            | Scheme '(' SchemeSpecificExpr ')'
923  *
924  * Scheme   ::=  NCName - 'xpointer' [VC: Non-XPointer schemes]
925  *
926  * SchemeSpecificExpr ::= StringWithBalancedParens
927  *
928  * StringWithBalancedParens ::=
929  *              [^()]* ('(' StringWithBalancedParens ')' [^()]*)*
930  *              [VC: Parenthesis escaping]
931  *
932  * XPtrExpr ::= Expr [VC: Parenthesis escaping]
933  *
934  * VC: Parenthesis escaping:
935  *   The end of an XPointer part is signaled by the right parenthesis ")"
936  *   character that is balanced with the left parenthesis "(" character
937  *   that began the part. Any unbalanced parenthesis character inside the
938  *   expression, even within literals, must be escaped with a circumflex (^)
939  *   character preceding it. If the expression contains any literal
940  *   occurrences of the circumflex, each must be escaped with an additional
941  *   circumflex (that is, ^^). If the unescaped parentheses in the expression
942  *   are not balanced, a syntax error results.
943  *
944  * Parse and evaluate an XPtrPart. Basically it generates the unescaped
945  * string and if the scheme is 'xpointer' it will call the XPath interpreter.
946  *
947  * TODO: there is no new scheme registration mechanism
948  */
949 
950 static void
951 xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt, xmlChar *name) {
952     xmlChar *buffer, *cur;
953     int len;
954     int level;
955 
956     if (name == NULL)
957     name = xmlXPathParseName(ctxt);
958     if (name == NULL)
959 	XP_ERROR(XPATH_EXPR_ERROR);
960 
961     if (CUR != '(') {
962         xmlFree(name);
963 	XP_ERROR(XPATH_EXPR_ERROR);
964     }
965     NEXT;
966     level = 1;
967 
968     len = xmlStrlen(ctxt->cur);
969     len++;
970     buffer = (xmlChar *) xmlMallocAtomic(len * sizeof (xmlChar));
971     if (buffer == NULL) {
972         xmlXPtrErrMemory("allocating buffer");
973         xmlFree(name);
974 	return;
975     }
976 
977     cur = buffer;
978     while (CUR != 0) {
979 	if (CUR == ')') {
980 	    level--;
981 	    if (level == 0) {
982 		NEXT;
983 		break;
984 	    }
985 	} else if (CUR == '(') {
986 	    level++;
987 	} else if (CUR == '^') {
988             if ((NXT(1) == ')') || (NXT(1) == '(') || (NXT(1) == '^')) {
989                 NEXT;
990             }
991 	}
992         *cur++ = CUR;
993 	NEXT;
994     }
995     *cur = 0;
996 
997     if ((level != 0) && (CUR == 0)) {
998         xmlFree(name);
999 	xmlFree(buffer);
1000 	XP_ERROR(XPTR_SYNTAX_ERROR);
1001     }
1002 
1003     if (xmlStrEqual(name, (xmlChar *) "xpointer")) {
1004 	const xmlChar *left = CUR_PTR;
1005 
1006 	CUR_PTR = buffer;
1007 	/*
1008 	 * To evaluate an xpointer scheme element (4.3) we need:
1009 	 *   context initialized to the root
1010 	 *   context position initalized to 1
1011 	 *   context size initialized to 1
1012 	 */
1013 	ctxt->context->node = (xmlNodePtr)ctxt->context->doc;
1014 	ctxt->context->proximityPosition = 1;
1015 	ctxt->context->contextSize = 1;
1016 	xmlXPathEvalExpr(ctxt);
1017 	CUR_PTR=left;
1018     } else if (xmlStrEqual(name, (xmlChar *) "element")) {
1019 	const xmlChar *left = CUR_PTR;
1020 	xmlChar *name2;
1021 
1022 	CUR_PTR = buffer;
1023 	if (buffer[0] == '/') {
1024 	    xmlXPathRoot(ctxt);
1025 	    xmlXPtrEvalChildSeq(ctxt, NULL);
1026 	} else {
1027 	    name2 = xmlXPathParseName(ctxt);
1028 	    if (name2 == NULL) {
1029 		CUR_PTR = left;
1030 		xmlFree(buffer);
1031                 xmlFree(name);
1032 		XP_ERROR(XPATH_EXPR_ERROR);
1033 	    }
1034 	    xmlXPtrEvalChildSeq(ctxt, name2);
1035 	}
1036 	CUR_PTR = left;
1037 #ifdef XPTR_XMLNS_SCHEME
1038     } else if (xmlStrEqual(name, (xmlChar *) "xmlns")) {
1039 	const xmlChar *left = CUR_PTR;
1040 	xmlChar *prefix;
1041 	xmlChar *URI;
1042 	xmlURIPtr value;
1043 
1044 	CUR_PTR = buffer;
1045         prefix = xmlXPathParseNCName(ctxt);
1046 	if (prefix == NULL) {
1047 	    xmlFree(buffer);
1048 	    xmlFree(name);
1049 	    XP_ERROR(XPTR_SYNTAX_ERROR);
1050 	}
1051 	SKIP_BLANKS;
1052 	if (CUR != '=') {
1053 	    xmlFree(prefix);
1054 	    xmlFree(buffer);
1055 	    xmlFree(name);
1056 	    XP_ERROR(XPTR_SYNTAX_ERROR);
1057 	}
1058 	NEXT;
1059 	SKIP_BLANKS;
1060 	/* @@ check escaping in the XPointer WD */
1061 
1062 	value = xmlParseURI((const char *)ctxt->cur);
1063 	if (value == NULL) {
1064 	    xmlFree(prefix);
1065 	    xmlFree(buffer);
1066 	    xmlFree(name);
1067 	    XP_ERROR(XPTR_SYNTAX_ERROR);
1068 	}
1069 	URI = xmlSaveUri(value);
1070 	xmlFreeURI(value);
1071 	if (URI == NULL) {
1072 	    xmlFree(prefix);
1073 	    xmlFree(buffer);
1074 	    xmlFree(name);
1075 	    XP_ERROR(XPATH_MEMORY_ERROR);
1076 	}
1077 
1078 	xmlXPathRegisterNs(ctxt->context, prefix, URI);
1079 	CUR_PTR = left;
1080 	xmlFree(URI);
1081 	xmlFree(prefix);
1082 #endif /* XPTR_XMLNS_SCHEME */
1083     } else {
1084         xmlXPtrErr(ctxt, XML_XPTR_UNKNOWN_SCHEME,
1085 		   "unsupported scheme '%s'\n", name);
1086     }
1087     xmlFree(buffer);
1088     xmlFree(name);
1089 }
1090 
1091 /**
1092  * xmlXPtrEvalFullXPtr:
1093  * @ctxt:  the XPointer Parser context
1094  * @name:  the preparsed Scheme for the first XPtrPart
1095  *
1096  * FullXPtr ::= XPtrPart (S? XPtrPart)*
1097  *
1098  * As the specs says:
1099  * -----------
1100  * When multiple XPtrParts are provided, they must be evaluated in
1101  * left-to-right order. If evaluation of one part fails, the nexti
1102  * is evaluated. The following conditions cause XPointer part failure:
1103  *
1104  * - An unknown scheme
1105  * - A scheme that does not locate any sub-resource present in the resource
1106  * - A scheme that is not applicable to the media type of the resource
1107  *
1108  * The XPointer application must consume a failed XPointer part and
1109  * attempt to evaluate the next one, if any. The result of the first
1110  * XPointer part whose evaluation succeeds is taken to be the fragment
1111  * located by the XPointer as a whole. If all the parts fail, the result
1112  * for the XPointer as a whole is a sub-resource error.
1113  * -----------
1114  *
1115  * Parse and evaluate a Full XPtr i.e. possibly a cascade of XPath based
1116  * expressions or other schemes.
1117  */
1118 static void
1119 xmlXPtrEvalFullXPtr(xmlXPathParserContextPtr ctxt, xmlChar *name) {
1120     if (name == NULL)
1121     name = xmlXPathParseName(ctxt);
1122     if (name == NULL)
1123 	XP_ERROR(XPATH_EXPR_ERROR);
1124     while (name != NULL) {
1125 	ctxt->error = XPATH_EXPRESSION_OK;
1126 	xmlXPtrEvalXPtrPart(ctxt, name);
1127 
1128 	/* in case of syntax error, break here */
1129 	if ((ctxt->error != XPATH_EXPRESSION_OK) &&
1130             (ctxt->error != XML_XPTR_UNKNOWN_SCHEME))
1131 	    return;
1132 
1133 	/*
1134 	 * If the returned value is a non-empty nodeset
1135 	 * or location set, return here.
1136 	 */
1137 	if (ctxt->value != NULL) {
1138 	    xmlXPathObjectPtr obj = ctxt->value;
1139 
1140 	    switch (obj->type) {
1141 		case XPATH_LOCATIONSET: {
1142 		    xmlLocationSetPtr loc = ctxt->value->user;
1143 		    if ((loc != NULL) && (loc->locNr > 0))
1144 			return;
1145 		    break;
1146 		}
1147 		case XPATH_NODESET: {
1148 		    xmlNodeSetPtr loc = ctxt->value->nodesetval;
1149 		    if ((loc != NULL) && (loc->nodeNr > 0))
1150 			return;
1151 		    break;
1152 		}
1153 		default:
1154 		    break;
1155 	    }
1156 
1157 	    /*
1158 	     * Evaluating to improper values is equivalent to
1159 	     * a sub-resource error, clean-up the stack
1160 	     */
1161 	    do {
1162 		obj = valuePop(ctxt);
1163 		if (obj != NULL) {
1164 		    xmlXPathFreeObject(obj);
1165 		}
1166 	    } while (obj != NULL);
1167 	}
1168 
1169 	/*
1170 	 * Is there another XPointer part.
1171 	 */
1172 	SKIP_BLANKS;
1173 	name = xmlXPathParseName(ctxt);
1174     }
1175 }
1176 
1177 /**
1178  * xmlXPtrEvalChildSeq:
1179  * @ctxt:  the XPointer Parser context
1180  * @name:  a possible ID name of the child sequence
1181  *
1182  *  ChildSeq ::= '/1' ('/' [0-9]*)*
1183  *             | Name ('/' [0-9]*)+
1184  *
1185  * Parse and evaluate a Child Sequence. This routine also handle the
1186  * case of a Bare Name used to get a document ID.
1187  */
1188 static void
1189 xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt, xmlChar *name) {
1190     /*
1191      * XPointer don't allow by syntax to address in mutirooted trees
1192      * this might prove useful in some cases, warn about it.
1193      */
1194     if ((name == NULL) && (CUR == '/') && (NXT(1) != '1')) {
1195         xmlXPtrErr(ctxt, XML_XPTR_CHILDSEQ_START,
1196 		   "warning: ChildSeq not starting by /1\n", NULL);
1197     }
1198 
1199     if (name != NULL) {
1200 	valuePush(ctxt, xmlXPathNewString(name));
1201 	xmlFree(name);
1202 	xmlXPathIdFunction(ctxt, 1);
1203 	CHECK_ERROR;
1204     }
1205 
1206     while (CUR == '/') {
1207 	int child = 0;
1208 	NEXT;
1209 
1210 	while ((CUR >= '0') && (CUR <= '9')) {
1211 	    child = child * 10 + (CUR - '0');
1212 	    NEXT;
1213 	}
1214 	xmlXPtrGetChildNo(ctxt, child);
1215     }
1216 }
1217 
1218 
1219 /**
1220  * xmlXPtrEvalXPointer:
1221  * @ctxt:  the XPointer Parser context
1222  *
1223  *  XPointer ::= Name
1224  *             | ChildSeq
1225  *             | FullXPtr
1226  *
1227  * Parse and evaluate an XPointer
1228  */
1229 static void
1230 xmlXPtrEvalXPointer(xmlXPathParserContextPtr ctxt) {
1231     if (ctxt->valueTab == NULL) {
1232 	/* Allocate the value stack */
1233 	ctxt->valueTab = (xmlXPathObjectPtr *)
1234 			 xmlMalloc(10 * sizeof(xmlXPathObjectPtr));
1235 	if (ctxt->valueTab == NULL) {
1236 	    xmlXPtrErrMemory("allocating evaluation context");
1237 	    return;
1238 	}
1239 	ctxt->valueNr = 0;
1240 	ctxt->valueMax = 10;
1241 	ctxt->value = NULL;
1242 	ctxt->valueFrame = 0;
1243     }
1244     SKIP_BLANKS;
1245     if (CUR == '/') {
1246 	xmlXPathRoot(ctxt);
1247         xmlXPtrEvalChildSeq(ctxt, NULL);
1248     } else {
1249 	xmlChar *name;
1250 
1251 	name = xmlXPathParseName(ctxt);
1252 	if (name == NULL)
1253 	    XP_ERROR(XPATH_EXPR_ERROR);
1254 	if (CUR == '(') {
1255 	    xmlXPtrEvalFullXPtr(ctxt, name);
1256 	    /* Short evaluation */
1257 	    return;
1258 	} else {
1259 	    /* this handle both Bare Names and Child Sequences */
1260 	    xmlXPtrEvalChildSeq(ctxt, name);
1261 	}
1262     }
1263     SKIP_BLANKS;
1264     if (CUR != 0)
1265 	XP_ERROR(XPATH_EXPR_ERROR);
1266 }
1267 
1268 
1269 /************************************************************************
1270  *									*
1271  *			General routines				*
1272  *									*
1273  ************************************************************************/
1274 
1275 static
1276 void xmlXPtrStringRangeFunction(xmlXPathParserContextPtr ctxt, int nargs);
1277 static
1278 void xmlXPtrStartPointFunction(xmlXPathParserContextPtr ctxt, int nargs);
1279 static
1280 void xmlXPtrEndPointFunction(xmlXPathParserContextPtr ctxt, int nargs);
1281 static
1282 void xmlXPtrHereFunction(xmlXPathParserContextPtr ctxt, int nargs);
1283 static
1284 void xmlXPtrOriginFunction(xmlXPathParserContextPtr ctxt, int nargs);
1285 static
1286 void xmlXPtrRangeInsideFunction(xmlXPathParserContextPtr ctxt, int nargs);
1287 static
1288 void xmlXPtrRangeFunction(xmlXPathParserContextPtr ctxt, int nargs);
1289 
1290 /**
1291  * xmlXPtrNewContext:
1292  * @doc:  the XML document
1293  * @here:  the node that directly contains the XPointer being evaluated or NULL
1294  * @origin:  the element from which a user or program initiated traversal of
1295  *           the link, or NULL.
1296  *
1297  * Create a new XPointer context
1298  *
1299  * Returns the xmlXPathContext just allocated.
1300  */
1301 xmlXPathContextPtr
1302 xmlXPtrNewContext(xmlDocPtr doc, xmlNodePtr here, xmlNodePtr origin) {
1303     xmlXPathContextPtr ret;
1304 
1305     ret = xmlXPathNewContext(doc);
1306     if (ret == NULL)
1307 	return(ret);
1308     ret->xptr = 1;
1309     ret->here = here;
1310     ret->origin = origin;
1311 
1312     xmlXPathRegisterFunc(ret, (xmlChar *)"range",
1313 	                 xmlXPtrRangeFunction);
1314     xmlXPathRegisterFunc(ret, (xmlChar *)"range-inside",
1315 	                 xmlXPtrRangeInsideFunction);
1316     xmlXPathRegisterFunc(ret, (xmlChar *)"string-range",
1317 	                 xmlXPtrStringRangeFunction);
1318     xmlXPathRegisterFunc(ret, (xmlChar *)"start-point",
1319 	                 xmlXPtrStartPointFunction);
1320     xmlXPathRegisterFunc(ret, (xmlChar *)"end-point",
1321 	                 xmlXPtrEndPointFunction);
1322     xmlXPathRegisterFunc(ret, (xmlChar *)"here",
1323 	                 xmlXPtrHereFunction);
1324     xmlXPathRegisterFunc(ret, (xmlChar *)" origin",
1325 	                 xmlXPtrOriginFunction);
1326 
1327     return(ret);
1328 }
1329 
1330 /**
1331  * xmlXPtrEval:
1332  * @str:  the XPointer expression
1333  * @ctx:  the XPointer context
1334  *
1335  * Evaluate the XPath Location Path in the given context.
1336  *
1337  * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
1338  *         the caller has to free the object.
1339  */
1340 xmlXPathObjectPtr
1341 xmlXPtrEval(const xmlChar *str, xmlXPathContextPtr ctx) {
1342     xmlXPathParserContextPtr ctxt;
1343     xmlXPathObjectPtr res = NULL, tmp;
1344     xmlXPathObjectPtr init = NULL;
1345     int stack = 0;
1346 
1347     xmlXPathInit();
1348 
1349     if ((ctx == NULL) || (str == NULL))
1350 	return(NULL);
1351 
1352     ctxt = xmlXPathNewParserContext(str, ctx);
1353     if (ctxt == NULL)
1354 	return(NULL);
1355     ctxt->xptr = 1;
1356     xmlXPtrEvalXPointer(ctxt);
1357 
1358     if ((ctxt->value != NULL) &&
1359 	(ctxt->value->type != XPATH_NODESET) &&
1360 	(ctxt->value->type != XPATH_LOCATIONSET)) {
1361         xmlXPtrErr(ctxt, XML_XPTR_EVAL_FAILED,
1362 		"xmlXPtrEval: evaluation failed to return a node set\n",
1363 		   NULL);
1364     } else {
1365 	res = valuePop(ctxt);
1366     }
1367 
1368     do {
1369         tmp = valuePop(ctxt);
1370 	if (tmp != NULL) {
1371 	    if (tmp != init) {
1372 		if (tmp->type == XPATH_NODESET) {
1373 		    /*
1374 		     * Evaluation may push a root nodeset which is unused
1375 		     */
1376 		    xmlNodeSetPtr set;
1377 		    set = tmp->nodesetval;
1378 		    if ((set == NULL) || (set->nodeNr != 1) ||
1379 			(set->nodeTab[0] != (xmlNodePtr) ctx->doc))
1380 			stack++;
1381 		} else
1382 		    stack++;
1383 	    }
1384 	    xmlXPathFreeObject(tmp);
1385         }
1386     } while (tmp != NULL);
1387     if (stack != 0) {
1388         xmlXPtrErr(ctxt, XML_XPTR_EXTRA_OBJECTS,
1389 		   "xmlXPtrEval: object(s) left on the eval stack\n",
1390 		   NULL);
1391     }
1392     if (ctxt->error != XPATH_EXPRESSION_OK) {
1393 	xmlXPathFreeObject(res);
1394 	res = NULL;
1395     }
1396 
1397     xmlXPathFreeParserContext(ctxt);
1398     return(res);
1399 }
1400 
1401 /**
1402  * xmlXPtrBuildRangeNodeList:
1403  * @range:  a range object
1404  *
1405  * Build a node list tree copy of the range
1406  *
1407  * Returns an xmlNodePtr list or NULL.
1408  *         the caller has to free the node tree.
1409  */
1410 static xmlNodePtr
1411 xmlXPtrBuildRangeNodeList(xmlXPathObjectPtr range) {
1412     /* pointers to generated nodes */
1413     xmlNodePtr list = NULL, last = NULL, parent = NULL, tmp;
1414     /* pointers to traversal nodes */
1415     xmlNodePtr start, cur, end;
1416     int index1, index2;
1417 
1418     if (range == NULL)
1419 	return(NULL);
1420     if (range->type != XPATH_RANGE)
1421 	return(NULL);
1422     start = (xmlNodePtr) range->user;
1423 
1424     if ((start == NULL) || (start->type == XML_NAMESPACE_DECL))
1425 	return(NULL);
1426     end = range->user2;
1427     if (end == NULL)
1428 	return(xmlCopyNode(start, 1));
1429     if (end->type == XML_NAMESPACE_DECL)
1430         return(NULL);
1431 
1432     cur = start;
1433     index1 = range->index;
1434     index2 = range->index2;
1435     while (cur != NULL) {
1436 	if (cur == end) {
1437 	    if (cur->type == XML_TEXT_NODE) {
1438 		const xmlChar *content = cur->content;
1439 		int len;
1440 
1441 		if (content == NULL) {
1442 		    tmp = xmlNewTextLen(NULL, 0);
1443 		} else {
1444 		    len = index2;
1445 		    if ((cur == start) && (index1 > 1)) {
1446 			content += (index1 - 1);
1447 			len -= (index1 - 1);
1448 			index1 = 0;
1449 		    } else {
1450 			len = index2;
1451 		    }
1452 		    tmp = xmlNewTextLen(content, len);
1453 		}
1454 		/* single sub text node selection */
1455 		if (list == NULL)
1456 		    return(tmp);
1457 		/* prune and return full set */
1458 		if (last != NULL)
1459 		    xmlAddNextSibling(last, tmp);
1460 		else
1461 		    xmlAddChild(parent, tmp);
1462 		return(list);
1463 	    } else {
1464 		tmp = xmlCopyNode(cur, 0);
1465 		if (list == NULL)
1466 		    list = tmp;
1467 		else {
1468 		    if (last != NULL)
1469 			xmlAddNextSibling(last, tmp);
1470 		    else
1471 			xmlAddChild(parent, tmp);
1472 		}
1473 		last = NULL;
1474 		parent = tmp;
1475 
1476 		if (index2 > 1) {
1477 		    end = xmlXPtrGetNthChild(cur, index2 - 1);
1478 		    index2 = 0;
1479 		}
1480 		if ((cur == start) && (index1 > 1)) {
1481 		    cur = xmlXPtrGetNthChild(cur, index1 - 1);
1482 		    index1 = 0;
1483 		} else {
1484 		    cur = cur->children;
1485 		}
1486 		/*
1487 		 * Now gather the remaining nodes from cur to end
1488 		 */
1489 		continue; /* while */
1490 	    }
1491 	} else if ((cur == start) &&
1492 		   (list == NULL) /* looks superfluous but ... */ ) {
1493 	    if ((cur->type == XML_TEXT_NODE) ||
1494 		(cur->type == XML_CDATA_SECTION_NODE)) {
1495 		const xmlChar *content = cur->content;
1496 
1497 		if (content == NULL) {
1498 		    tmp = xmlNewTextLen(NULL, 0);
1499 		} else {
1500 		    if (index1 > 1) {
1501 			content += (index1 - 1);
1502 		    }
1503 		    tmp = xmlNewText(content);
1504 		}
1505 		last = list = tmp;
1506 	    } else {
1507 		if ((cur == start) && (index1 > 1)) {
1508 		    tmp = xmlCopyNode(cur, 0);
1509 		    list = tmp;
1510 		    parent = tmp;
1511 		    last = NULL;
1512 		    cur = xmlXPtrGetNthChild(cur, index1 - 1);
1513 		    index1 = 0;
1514 		    /*
1515 		     * Now gather the remaining nodes from cur to end
1516 		     */
1517 		    continue; /* while */
1518 		}
1519 		tmp = xmlCopyNode(cur, 1);
1520 		list = tmp;
1521 		parent = NULL;
1522 		last = tmp;
1523 	    }
1524 	} else {
1525 	    tmp = NULL;
1526 	    switch (cur->type) {
1527 		case XML_DTD_NODE:
1528 		case XML_ELEMENT_DECL:
1529 		case XML_ATTRIBUTE_DECL:
1530 		case XML_ENTITY_NODE:
1531 		    /* Do not copy DTD informations */
1532 		    break;
1533 		case XML_ENTITY_DECL:
1534 		    TODO /* handle crossing entities -> stack needed */
1535 		    break;
1536 		case XML_XINCLUDE_START:
1537 		case XML_XINCLUDE_END:
1538 		    /* don't consider it part of the tree content */
1539 		    break;
1540 		case XML_ATTRIBUTE_NODE:
1541 		    /* Humm, should not happen ! */
1542 		    STRANGE
1543 		    break;
1544 		default:
1545 		    tmp = xmlCopyNode(cur, 1);
1546 		    break;
1547 	    }
1548 	    if (tmp != NULL) {
1549 		if ((list == NULL) || ((last == NULL) && (parent == NULL)))  {
1550 		    STRANGE
1551 		    return(NULL);
1552 		}
1553 		if (last != NULL)
1554 		    xmlAddNextSibling(last, tmp);
1555 		else {
1556 		    xmlAddChild(parent, tmp);
1557 		    last = tmp;
1558 		}
1559 	    }
1560 	}
1561 	/*
1562 	 * Skip to next node in document order
1563 	 */
1564 	if ((list == NULL) || ((last == NULL) && (parent == NULL)))  {
1565 	    STRANGE
1566 	    return(NULL);
1567 	}
1568 	cur = xmlXPtrAdvanceNode(cur, NULL);
1569     }
1570     return(list);
1571 }
1572 
1573 /**
1574  * xmlXPtrBuildNodeList:
1575  * @obj:  the XPointer result from the evaluation.
1576  *
1577  * Build a node list tree copy of the XPointer result.
1578  * This will drop Attributes and Namespace declarations.
1579  *
1580  * Returns an xmlNodePtr list or NULL.
1581  *         the caller has to free the node tree.
1582  */
1583 xmlNodePtr
1584 xmlXPtrBuildNodeList(xmlXPathObjectPtr obj) {
1585     xmlNodePtr list = NULL, last = NULL;
1586     int i;
1587 
1588     if (obj == NULL)
1589 	return(NULL);
1590     switch (obj->type) {
1591         case XPATH_NODESET: {
1592 	    xmlNodeSetPtr set = obj->nodesetval;
1593 	    if (set == NULL)
1594 		return(NULL);
1595 	    for (i = 0;i < set->nodeNr;i++) {
1596 		if (set->nodeTab[i] == NULL)
1597 		    continue;
1598 		switch (set->nodeTab[i]->type) {
1599 		    case XML_TEXT_NODE:
1600 		    case XML_CDATA_SECTION_NODE:
1601 		    case XML_ELEMENT_NODE:
1602 		    case XML_ENTITY_REF_NODE:
1603 		    case XML_ENTITY_NODE:
1604 		    case XML_PI_NODE:
1605 		    case XML_COMMENT_NODE:
1606 		    case XML_DOCUMENT_NODE:
1607 		    case XML_HTML_DOCUMENT_NODE:
1608 #ifdef LIBXML_DOCB_ENABLED
1609 		    case XML_DOCB_DOCUMENT_NODE:
1610 #endif
1611 		    case XML_XINCLUDE_START:
1612 		    case XML_XINCLUDE_END:
1613 			break;
1614 		    case XML_ATTRIBUTE_NODE:
1615 		    case XML_NAMESPACE_DECL:
1616 		    case XML_DOCUMENT_TYPE_NODE:
1617 		    case XML_DOCUMENT_FRAG_NODE:
1618 		    case XML_NOTATION_NODE:
1619 		    case XML_DTD_NODE:
1620 		    case XML_ELEMENT_DECL:
1621 		    case XML_ATTRIBUTE_DECL:
1622 		    case XML_ENTITY_DECL:
1623 			continue; /* for */
1624 		}
1625 		if (last == NULL)
1626 		    list = last = xmlCopyNode(set->nodeTab[i], 1);
1627 		else {
1628 		    xmlAddNextSibling(last, xmlCopyNode(set->nodeTab[i], 1));
1629 		    if (last->next != NULL)
1630 			last = last->next;
1631 		}
1632 	    }
1633 	    break;
1634 	}
1635 	case XPATH_LOCATIONSET: {
1636 	    xmlLocationSetPtr set = (xmlLocationSetPtr) obj->user;
1637 	    if (set == NULL)
1638 		return(NULL);
1639 	    for (i = 0;i < set->locNr;i++) {
1640 		if (last == NULL)
1641 		    list = last = xmlXPtrBuildNodeList(set->locTab[i]);
1642 		else
1643 		    xmlAddNextSibling(last,
1644 			    xmlXPtrBuildNodeList(set->locTab[i]));
1645 		if (last != NULL) {
1646 		    while (last->next != NULL)
1647 			last = last->next;
1648 		}
1649 	    }
1650 	    break;
1651 	}
1652 	case XPATH_RANGE:
1653 	    return(xmlXPtrBuildRangeNodeList(obj));
1654 	case XPATH_POINT:
1655 	    return(xmlCopyNode(obj->user, 0));
1656 	default:
1657 	    break;
1658     }
1659     return(list);
1660 }
1661 
1662 /************************************************************************
1663  *									*
1664  *			XPointer functions				*
1665  *									*
1666  ************************************************************************/
1667 
1668 /**
1669  * xmlXPtrNbLocChildren:
1670  * @node:  an xmlNodePtr
1671  *
1672  * Count the number of location children of @node or the length of the
1673  * string value in case of text/PI/Comments nodes
1674  *
1675  * Returns the number of location children
1676  */
1677 static int
1678 xmlXPtrNbLocChildren(xmlNodePtr node) {
1679     int ret = 0;
1680     if (node == NULL)
1681 	return(-1);
1682     switch (node->type) {
1683         case XML_HTML_DOCUMENT_NODE:
1684         case XML_DOCUMENT_NODE:
1685         case XML_ELEMENT_NODE:
1686 	    node = node->children;
1687 	    while (node != NULL) {
1688 		if (node->type == XML_ELEMENT_NODE)
1689 		    ret++;
1690 		node = node->next;
1691 	    }
1692 	    break;
1693         case XML_ATTRIBUTE_NODE:
1694 	    return(-1);
1695 
1696         case XML_PI_NODE:
1697         case XML_COMMENT_NODE:
1698         case XML_TEXT_NODE:
1699         case XML_CDATA_SECTION_NODE:
1700         case XML_ENTITY_REF_NODE:
1701 	    ret = xmlStrlen(node->content);
1702 	    break;
1703 	default:
1704 	    return(-1);
1705     }
1706     return(ret);
1707 }
1708 
1709 /**
1710  * xmlXPtrHereFunction:
1711  * @ctxt:  the XPointer Parser context
1712  * @nargs:  the number of args
1713  *
1714  * Function implementing here() operation
1715  * as described in 5.4.3
1716  */
1717 static void
1718 xmlXPtrHereFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1719     CHECK_ARITY(0);
1720 
1721     if (ctxt->context->here == NULL)
1722 	XP_ERROR(XPTR_SYNTAX_ERROR);
1723 
1724     valuePush(ctxt, xmlXPtrNewLocationSetNodes(ctxt->context->here, NULL));
1725 }
1726 
1727 /**
1728  * xmlXPtrOriginFunction:
1729  * @ctxt:  the XPointer Parser context
1730  * @nargs:  the number of args
1731  *
1732  * Function implementing origin() operation
1733  * as described in 5.4.3
1734  */
1735 static void
1736 xmlXPtrOriginFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1737     CHECK_ARITY(0);
1738 
1739     if (ctxt->context->origin == NULL)
1740 	XP_ERROR(XPTR_SYNTAX_ERROR);
1741 
1742     valuePush(ctxt, xmlXPtrNewLocationSetNodes(ctxt->context->origin, NULL));
1743 }
1744 
1745 /**
1746  * xmlXPtrStartPointFunction:
1747  * @ctxt:  the XPointer Parser context
1748  * @nargs:  the number of args
1749  *
1750  * Function implementing start-point() operation
1751  * as described in 5.4.3
1752  * ----------------
1753  * location-set start-point(location-set)
1754  *
1755  * For each location x in the argument location-set, start-point adds a
1756  * location of type point to the result location-set. That point represents
1757  * the start point of location x and is determined by the following rules:
1758  *
1759  * - If x is of type point, the start point is x.
1760  * - If x is of type range, the start point is the start point of x.
1761  * - If x is of type root, element, text, comment, or processing instruction,
1762  * - the container node of the start point is x and the index is 0.
1763  * - If x is of type attribute or namespace, the function must signal a
1764  *   syntax error.
1765  * ----------------
1766  *
1767  */
1768 static void
1769 xmlXPtrStartPointFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1770     xmlXPathObjectPtr tmp, obj, point;
1771     xmlLocationSetPtr newset = NULL;
1772     xmlLocationSetPtr oldset = NULL;
1773 
1774     CHECK_ARITY(1);
1775     if ((ctxt->value == NULL) ||
1776 	((ctxt->value->type != XPATH_LOCATIONSET) &&
1777 	 (ctxt->value->type != XPATH_NODESET)))
1778         XP_ERROR(XPATH_INVALID_TYPE)
1779 
1780     obj = valuePop(ctxt);
1781     if (obj->type == XPATH_NODESET) {
1782 	/*
1783 	 * First convert to a location set
1784 	 */
1785 	tmp = xmlXPtrNewLocationSetNodeSet(obj->nodesetval);
1786 	xmlXPathFreeObject(obj);
1787 	if (tmp == NULL)
1788             XP_ERROR(XPATH_MEMORY_ERROR)
1789 	obj = tmp;
1790     }
1791 
1792     newset = xmlXPtrLocationSetCreate(NULL);
1793     if (newset == NULL) {
1794 	xmlXPathFreeObject(obj);
1795         XP_ERROR(XPATH_MEMORY_ERROR);
1796     }
1797     oldset = (xmlLocationSetPtr) obj->user;
1798     if (oldset != NULL) {
1799 	int i;
1800 
1801 	for (i = 0; i < oldset->locNr; i++) {
1802 	    tmp = oldset->locTab[i];
1803 	    if (tmp == NULL)
1804 		continue;
1805 	    point = NULL;
1806 	    switch (tmp->type) {
1807 		case XPATH_POINT:
1808 		    point = xmlXPtrNewPoint(tmp->user, tmp->index);
1809 		    break;
1810 		case XPATH_RANGE: {
1811 		    xmlNodePtr node = tmp->user;
1812 		    if (node != NULL) {
1813 			if ((node->type == XML_ATTRIBUTE_NODE) ||
1814                             (node->type == XML_NAMESPACE_DECL)) {
1815 			    xmlXPathFreeObject(obj);
1816 			    xmlXPtrFreeLocationSet(newset);
1817 			    XP_ERROR(XPTR_SYNTAX_ERROR);
1818 			}
1819 			point = xmlXPtrNewPoint(node, tmp->index);
1820 		    }
1821 		    break;
1822 	        }
1823 		default:
1824 		    /*** Should we raise an error ?
1825 		    xmlXPathFreeObject(obj);
1826 		    xmlXPathFreeObject(newset);
1827 		    XP_ERROR(XPATH_INVALID_TYPE)
1828 		    ***/
1829 		    break;
1830 	    }
1831             if (point != NULL)
1832 		xmlXPtrLocationSetAdd(newset, point);
1833 	}
1834     }
1835     xmlXPathFreeObject(obj);
1836     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
1837 }
1838 
1839 /**
1840  * xmlXPtrEndPointFunction:
1841  * @ctxt:  the XPointer Parser context
1842  * @nargs:  the number of args
1843  *
1844  * Function implementing end-point() operation
1845  * as described in 5.4.3
1846  * ----------------------------
1847  * location-set end-point(location-set)
1848  *
1849  * For each location x in the argument location-set, end-point adds a
1850  * location of type point to the result location-set. That point represents
1851  * the end point of location x and is determined by the following rules:
1852  *
1853  * - If x is of type point, the resulting point is x.
1854  * - If x is of type range, the resulting point is the end point of x.
1855  * - If x is of type root or element, the container node of the resulting
1856  *   point is x and the index is the number of location children of x.
1857  * - If x is of type text, comment, or processing instruction, the container
1858  *   node of the resulting point is x and the index is the length of the
1859  *   string-value of x.
1860  * - If x is of type attribute or namespace, the function must signal a
1861  *   syntax error.
1862  * ----------------------------
1863  */
1864 static void
1865 xmlXPtrEndPointFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1866     xmlXPathObjectPtr tmp, obj, point;
1867     xmlLocationSetPtr newset = NULL;
1868     xmlLocationSetPtr oldset = NULL;
1869 
1870     CHECK_ARITY(1);
1871     if ((ctxt->value == NULL) ||
1872 	((ctxt->value->type != XPATH_LOCATIONSET) &&
1873 	 (ctxt->value->type != XPATH_NODESET)))
1874         XP_ERROR(XPATH_INVALID_TYPE)
1875 
1876     obj = valuePop(ctxt);
1877     if (obj->type == XPATH_NODESET) {
1878 	/*
1879 	 * First convert to a location set
1880 	 */
1881 	tmp = xmlXPtrNewLocationSetNodeSet(obj->nodesetval);
1882 	xmlXPathFreeObject(obj);
1883 	if (tmp == NULL)
1884             XP_ERROR(XPATH_MEMORY_ERROR)
1885 	obj = tmp;
1886     }
1887 
1888     newset = xmlXPtrLocationSetCreate(NULL);
1889     if (newset == NULL) {
1890 	xmlXPathFreeObject(obj);
1891         XP_ERROR(XPATH_MEMORY_ERROR);
1892     }
1893     oldset = (xmlLocationSetPtr) obj->user;
1894     if (oldset != NULL) {
1895 	int i;
1896 
1897 	for (i = 0; i < oldset->locNr; i++) {
1898 	    tmp = oldset->locTab[i];
1899 	    if (tmp == NULL)
1900 		continue;
1901 	    point = NULL;
1902 	    switch (tmp->type) {
1903 		case XPATH_POINT:
1904 		    point = xmlXPtrNewPoint(tmp->user, tmp->index);
1905 		    break;
1906 		case XPATH_RANGE: {
1907 		    xmlNodePtr node = tmp->user2;
1908 		    if (node != NULL) {
1909 			if ((node->type == XML_ATTRIBUTE_NODE) ||
1910                             (node->type == XML_NAMESPACE_DECL)) {
1911 			    xmlXPathFreeObject(obj);
1912 			    xmlXPtrFreeLocationSet(newset);
1913 			    XP_ERROR(XPTR_SYNTAX_ERROR);
1914 			}
1915 			point = xmlXPtrNewPoint(node, tmp->index2);
1916 		    } else if (tmp->user == NULL) {
1917 			point = xmlXPtrNewPoint(node,
1918 				       xmlXPtrNbLocChildren(node));
1919 		    }
1920 		    break;
1921 	        }
1922 		default:
1923 		    /*** Should we raise an error ?
1924 		    xmlXPathFreeObject(obj);
1925 		    xmlXPathFreeObject(newset);
1926 		    XP_ERROR(XPATH_INVALID_TYPE)
1927 		    ***/
1928 		    break;
1929 	    }
1930             if (point != NULL)
1931 		xmlXPtrLocationSetAdd(newset, point);
1932 	}
1933     }
1934     xmlXPathFreeObject(obj);
1935     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
1936 }
1937 
1938 
1939 /**
1940  * xmlXPtrCoveringRange:
1941  * @ctxt:  the XPointer Parser context
1942  * @loc:  the location for which the covering range must be computed
1943  *
1944  * A covering range is a range that wholly encompasses a location
1945  * Section 5.3.3. Covering Ranges for All Location Types
1946  *        http://www.w3.org/TR/xptr#N2267
1947  *
1948  * Returns a new location or NULL in case of error
1949  */
1950 static xmlXPathObjectPtr
1951 xmlXPtrCoveringRange(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr loc) {
1952     if (loc == NULL)
1953 	return(NULL);
1954     if ((ctxt == NULL) || (ctxt->context == NULL) ||
1955 	(ctxt->context->doc == NULL))
1956 	return(NULL);
1957     switch (loc->type) {
1958         case XPATH_POINT:
1959 	    return(xmlXPtrNewRange(loc->user, loc->index,
1960 			           loc->user, loc->index));
1961         case XPATH_RANGE:
1962 	    if (loc->user2 != NULL) {
1963 		return(xmlXPtrNewRange(loc->user, loc->index,
1964 			              loc->user2, loc->index2));
1965 	    } else {
1966 		xmlNodePtr node = (xmlNodePtr) loc->user;
1967 		if (node == (xmlNodePtr) ctxt->context->doc) {
1968 		    return(xmlXPtrNewRange(node, 0, node,
1969 					   xmlXPtrGetArity(node)));
1970 		} else {
1971 		    switch (node->type) {
1972 			case XML_ATTRIBUTE_NODE:
1973 			/* !!! our model is slightly different than XPath */
1974 			    return(xmlXPtrNewRange(node, 0, node,
1975 					           xmlXPtrGetArity(node)));
1976 			case XML_ELEMENT_NODE:
1977 			case XML_TEXT_NODE:
1978 			case XML_CDATA_SECTION_NODE:
1979 			case XML_ENTITY_REF_NODE:
1980 			case XML_PI_NODE:
1981 			case XML_COMMENT_NODE:
1982 			case XML_DOCUMENT_NODE:
1983 			case XML_NOTATION_NODE:
1984 			case XML_HTML_DOCUMENT_NODE: {
1985 			    int indx = xmlXPtrGetIndex(node);
1986 
1987 			    node = node->parent;
1988 			    return(xmlXPtrNewRange(node, indx - 1,
1989 					           node, indx + 1));
1990 			}
1991 			default:
1992 			    return(NULL);
1993 		    }
1994 		}
1995 	    }
1996 	default:
1997 	    TODO /* missed one case ??? */
1998     }
1999     return(NULL);
2000 }
2001 
2002 /**
2003  * xmlXPtrRangeFunction:
2004  * @ctxt:  the XPointer Parser context
2005  * @nargs:  the number of args
2006  *
2007  * Function implementing the range() function 5.4.3
2008  *  location-set range(location-set )
2009  *
2010  *  The range function returns ranges covering the locations in
2011  *  the argument location-set. For each location x in the argument
2012  *  location-set, a range location representing the covering range of
2013  *  x is added to the result location-set.
2014  */
2015 static void
2016 xmlXPtrRangeFunction(xmlXPathParserContextPtr ctxt, int nargs) {
2017     int i;
2018     xmlXPathObjectPtr set;
2019     xmlLocationSetPtr oldset;
2020     xmlLocationSetPtr newset;
2021 
2022     CHECK_ARITY(1);
2023     if ((ctxt->value == NULL) ||
2024 	((ctxt->value->type != XPATH_LOCATIONSET) &&
2025 	 (ctxt->value->type != XPATH_NODESET)))
2026         XP_ERROR(XPATH_INVALID_TYPE)
2027 
2028     set = valuePop(ctxt);
2029     if (set->type == XPATH_NODESET) {
2030 	xmlXPathObjectPtr tmp;
2031 
2032 	/*
2033 	 * First convert to a location set
2034 	 */
2035 	tmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);
2036 	xmlXPathFreeObject(set);
2037 	if (tmp == NULL)
2038             XP_ERROR(XPATH_MEMORY_ERROR)
2039 	set = tmp;
2040     }
2041     oldset = (xmlLocationSetPtr) set->user;
2042 
2043     /*
2044      * The loop is to compute the covering range for each item and add it
2045      */
2046     newset = xmlXPtrLocationSetCreate(NULL);
2047     if (newset == NULL) {
2048 	xmlXPathFreeObject(set);
2049         XP_ERROR(XPATH_MEMORY_ERROR);
2050     }
2051     if (oldset != NULL) {
2052         for (i = 0;i < oldset->locNr;i++) {
2053             xmlXPtrLocationSetAdd(newset,
2054                     xmlXPtrCoveringRange(ctxt, oldset->locTab[i]));
2055         }
2056     }
2057 
2058     /*
2059      * Save the new value and cleanup
2060      */
2061     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2062     xmlXPathFreeObject(set);
2063 }
2064 
2065 /**
2066  * xmlXPtrInsideRange:
2067  * @ctxt:  the XPointer Parser context
2068  * @loc:  the location for which the inside range must be computed
2069  *
2070  * A inside range is a range described in the range-inside() description
2071  *
2072  * Returns a new location or NULL in case of error
2073  */
2074 static xmlXPathObjectPtr
2075 xmlXPtrInsideRange(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr loc) {
2076     if (loc == NULL)
2077 	return(NULL);
2078     if ((ctxt == NULL) || (ctxt->context == NULL) ||
2079 	(ctxt->context->doc == NULL))
2080 	return(NULL);
2081     switch (loc->type) {
2082         case XPATH_POINT: {
2083 	    xmlNodePtr node = (xmlNodePtr) loc->user;
2084 	    switch (node->type) {
2085 		case XML_PI_NODE:
2086 		case XML_COMMENT_NODE:
2087 		case XML_TEXT_NODE:
2088 		case XML_CDATA_SECTION_NODE: {
2089 		    if (node->content == NULL) {
2090 			return(xmlXPtrNewRange(node, 0, node, 0));
2091 		    } else {
2092 			return(xmlXPtrNewRange(node, 0, node,
2093 					       xmlStrlen(node->content)));
2094 		    }
2095 		}
2096 		case XML_ATTRIBUTE_NODE:
2097 		case XML_ELEMENT_NODE:
2098 		case XML_ENTITY_REF_NODE:
2099 		case XML_DOCUMENT_NODE:
2100 		case XML_NOTATION_NODE:
2101 		case XML_HTML_DOCUMENT_NODE: {
2102 		    return(xmlXPtrNewRange(node, 0, node,
2103 					   xmlXPtrGetArity(node)));
2104 		}
2105 		default:
2106 		    break;
2107 	    }
2108 	    return(NULL);
2109 	}
2110         case XPATH_RANGE: {
2111 	    xmlNodePtr node = (xmlNodePtr) loc->user;
2112 	    if (loc->user2 != NULL) {
2113 		return(xmlXPtrNewRange(node, loc->index,
2114 			               loc->user2, loc->index2));
2115 	    } else {
2116 		switch (node->type) {
2117 		    case XML_PI_NODE:
2118 		    case XML_COMMENT_NODE:
2119 		    case XML_TEXT_NODE:
2120 		    case XML_CDATA_SECTION_NODE: {
2121 			if (node->content == NULL) {
2122 			    return(xmlXPtrNewRange(node, 0, node, 0));
2123 			} else {
2124 			    return(xmlXPtrNewRange(node, 0, node,
2125 						   xmlStrlen(node->content)));
2126 			}
2127 		    }
2128 		    case XML_ATTRIBUTE_NODE:
2129 		    case XML_ELEMENT_NODE:
2130 		    case XML_ENTITY_REF_NODE:
2131 		    case XML_DOCUMENT_NODE:
2132 		    case XML_NOTATION_NODE:
2133 		    case XML_HTML_DOCUMENT_NODE: {
2134 			return(xmlXPtrNewRange(node, 0, node,
2135 					       xmlXPtrGetArity(node)));
2136 		    }
2137 		    default:
2138 			break;
2139 		}
2140 		return(NULL);
2141 	    }
2142         }
2143 	default:
2144 	    TODO /* missed one case ??? */
2145     }
2146     return(NULL);
2147 }
2148 
2149 /**
2150  * xmlXPtrRangeInsideFunction:
2151  * @ctxt:  the XPointer Parser context
2152  * @nargs:  the number of args
2153  *
2154  * Function implementing the range-inside() function 5.4.3
2155  *  location-set range-inside(location-set )
2156  *
2157  *  The range-inside function returns ranges covering the contents of
2158  *  the locations in the argument location-set. For each location x in
2159  *  the argument location-set, a range location is added to the result
2160  *  location-set. If x is a range location, then x is added to the
2161  *  result location-set. If x is not a range location, then x is used
2162  *  as the container location of the start and end points of the range
2163  *  location to be added; the index of the start point of the range is
2164  *  zero; if the end point is a character point then its index is the
2165  *  length of the string-value of x, and otherwise is the number of
2166  *  location children of x.
2167  *
2168  */
2169 static void
2170 xmlXPtrRangeInsideFunction(xmlXPathParserContextPtr ctxt, int nargs) {
2171     int i;
2172     xmlXPathObjectPtr set;
2173     xmlLocationSetPtr oldset;
2174     xmlLocationSetPtr newset;
2175 
2176     CHECK_ARITY(1);
2177     if ((ctxt->value == NULL) ||
2178 	((ctxt->value->type != XPATH_LOCATIONSET) &&
2179 	 (ctxt->value->type != XPATH_NODESET)))
2180         XP_ERROR(XPATH_INVALID_TYPE)
2181 
2182     set = valuePop(ctxt);
2183     if (set->type == XPATH_NODESET) {
2184 	xmlXPathObjectPtr tmp;
2185 
2186 	/*
2187 	 * First convert to a location set
2188 	 */
2189 	tmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);
2190 	xmlXPathFreeObject(set);
2191 	if (tmp == NULL)
2192 	     XP_ERROR(XPATH_MEMORY_ERROR)
2193 	set = tmp;
2194     }
2195     oldset = (xmlLocationSetPtr) set->user;
2196 
2197     /*
2198      * The loop is to compute the covering range for each item and add it
2199      */
2200     newset = xmlXPtrLocationSetCreate(NULL);
2201     if (newset == NULL) {
2202 	xmlXPathFreeObject(set);
2203         XP_ERROR(XPATH_MEMORY_ERROR);
2204     }
2205     for (i = 0;i < oldset->locNr;i++) {
2206 	xmlXPtrLocationSetAdd(newset,
2207 		xmlXPtrInsideRange(ctxt, oldset->locTab[i]));
2208     }
2209 
2210     /*
2211      * Save the new value and cleanup
2212      */
2213     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2214     xmlXPathFreeObject(set);
2215 }
2216 
2217 /**
2218  * xmlXPtrRangeToFunction:
2219  * @ctxt:  the XPointer Parser context
2220  * @nargs:  the number of args
2221  *
2222  * Implement the range-to() XPointer function
2223  *
2224  * Obsolete. range-to is not a real function but a special type of location
2225  * step which is handled in xpath.c.
2226  */
2227 void
2228 xmlXPtrRangeToFunction(xmlXPathParserContextPtr ctxt,
2229                        int nargs ATTRIBUTE_UNUSED) {
2230     XP_ERROR(XPATH_EXPR_ERROR);
2231 }
2232 
2233 /**
2234  * xmlXPtrAdvanceNode:
2235  * @cur:  the node
2236  * @level: incremented/decremented to show level in tree
2237  *
2238  * Advance to the next element or text node in document order
2239  * TODO: add a stack for entering/exiting entities
2240  *
2241  * Returns -1 in case of failure, 0 otherwise
2242  */
2243 xmlNodePtr
2244 xmlXPtrAdvanceNode(xmlNodePtr cur, int *level) {
2245 next:
2246     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
2247 	return(NULL);
2248     if (cur->children != NULL) {
2249         cur = cur->children ;
2250 	if (level != NULL)
2251 	    (*level)++;
2252 	goto found;
2253     }
2254 skip:		/* This label should only be needed if something is wrong! */
2255     if (cur->next != NULL) {
2256 	cur = cur->next;
2257 	goto found;
2258     }
2259     do {
2260         cur = cur->parent;
2261 	if (level != NULL)
2262 	    (*level)--;
2263         if (cur == NULL) return(NULL);
2264         if (cur->next != NULL) {
2265 	    cur = cur->next;
2266 	    goto found;
2267 	}
2268     } while (cur != NULL);
2269 
2270 found:
2271     if ((cur->type != XML_ELEMENT_NODE) &&
2272 	(cur->type != XML_TEXT_NODE) &&
2273 	(cur->type != XML_DOCUMENT_NODE) &&
2274 	(cur->type != XML_HTML_DOCUMENT_NODE) &&
2275 	(cur->type != XML_CDATA_SECTION_NODE)) {
2276 	    if (cur->type == XML_ENTITY_REF_NODE) {	/* Shouldn't happen */
2277 		TODO
2278 		goto skip;
2279 	    }
2280 	    goto next;
2281 	}
2282     return(cur);
2283 }
2284 
2285 /**
2286  * xmlXPtrAdvanceChar:
2287  * @node:  the node
2288  * @indx:  the indx
2289  * @bytes:  the number of bytes
2290  *
2291  * Advance a point of the associated number of bytes (not UTF8 chars)
2292  *
2293  * Returns -1 in case of failure, 0 otherwise
2294  */
2295 static int
2296 xmlXPtrAdvanceChar(xmlNodePtr *node, int *indx, int bytes) {
2297     xmlNodePtr cur;
2298     int pos;
2299     int len;
2300 
2301     if ((node == NULL) || (indx == NULL))
2302 	return(-1);
2303     cur = *node;
2304     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
2305 	return(-1);
2306     pos = *indx;
2307 
2308     while (bytes >= 0) {
2309 	/*
2310 	 * First position to the beginning of the first text node
2311 	 * corresponding to this point
2312 	 */
2313 	while ((cur != NULL) &&
2314 	       ((cur->type == XML_ELEMENT_NODE) ||
2315 	        (cur->type == XML_DOCUMENT_NODE) ||
2316 	        (cur->type == XML_HTML_DOCUMENT_NODE))) {
2317 	    if (pos > 0) {
2318 		cur = xmlXPtrGetNthChild(cur, pos);
2319 		pos = 0;
2320 	    } else {
2321 		cur = xmlXPtrAdvanceNode(cur, NULL);
2322 		pos = 0;
2323 	    }
2324 	}
2325 
2326 	if (cur == NULL) {
2327 	    *node = NULL;
2328 	    *indx = 0;
2329 	    return(-1);
2330 	}
2331 
2332 	/*
2333 	 * if there is no move needed return the current value.
2334 	 */
2335 	if (pos == 0) pos = 1;
2336 	if (bytes == 0) {
2337 	    *node = cur;
2338 	    *indx = pos;
2339 	    return(0);
2340 	}
2341 	/*
2342 	 * We should have a text (or cdata) node ...
2343 	 */
2344 	len = 0;
2345 	if ((cur->type != XML_ELEMENT_NODE) &&
2346             (cur->content != NULL)) {
2347 	    len = xmlStrlen(cur->content);
2348 	}
2349 	if (pos > len) {
2350 	    /* Strange, the indx in the text node is greater than it's len */
2351 	    STRANGE
2352 	    pos = len;
2353 	}
2354 	if (pos + bytes >= len) {
2355 	    bytes -= (len - pos);
2356 	    cur = xmlXPtrAdvanceNode(cur, NULL);
2357 	    pos = 0;
2358 	} else if (pos + bytes < len) {
2359 	    pos += bytes;
2360 	    *node = cur;
2361 	    *indx = pos;
2362 	    return(0);
2363 	}
2364     }
2365     return(-1);
2366 }
2367 
2368 /**
2369  * xmlXPtrMatchString:
2370  * @string:  the string to search
2371  * @start:  the start textnode
2372  * @startindex:  the start index
2373  * @end:  the end textnode IN/OUT
2374  * @endindex:  the end index IN/OUT
2375  *
2376  * Check whether the document contains @string at the position
2377  * (@start, @startindex) and limited by the (@end, @endindex) point
2378  *
2379  * Returns -1 in case of failure, 0 if not found, 1 if found in which case
2380  *            (@start, @startindex) will indicate the position of the beginning
2381  *            of the range and (@end, @endindex) will indicate the end
2382  *            of the range
2383  */
2384 static int
2385 xmlXPtrMatchString(const xmlChar *string, xmlNodePtr start, int startindex,
2386 	            xmlNodePtr *end, int *endindex) {
2387     xmlNodePtr cur;
2388     int pos; /* 0 based */
2389     int len; /* in bytes */
2390     int stringlen; /* in bytes */
2391     int match;
2392 
2393     if (string == NULL)
2394 	return(-1);
2395     if ((start == NULL) || (start->type == XML_NAMESPACE_DECL))
2396 	return(-1);
2397     if ((end == NULL) || (*end == NULL) ||
2398         ((*end)->type == XML_NAMESPACE_DECL) || (endindex == NULL))
2399 	return(-1);
2400     cur = start;
2401     pos = startindex - 1;
2402     stringlen = xmlStrlen(string);
2403 
2404     while (stringlen > 0) {
2405 	if ((cur == *end) && (pos + stringlen > *endindex))
2406 	    return(0);
2407 
2408 	if ((cur->type != XML_ELEMENT_NODE) && (cur->content != NULL)) {
2409 	    len = xmlStrlen(cur->content);
2410 	    if (len >= pos + stringlen) {
2411 		match = (!xmlStrncmp(&cur->content[pos], string, stringlen));
2412 		if (match) {
2413 #ifdef DEBUG_RANGES
2414 		    xmlGenericError(xmlGenericErrorContext,
2415 			    "found range %d bytes at index %d of ->",
2416 			    stringlen, pos + 1);
2417 		    xmlDebugDumpString(stdout, cur->content);
2418 		    xmlGenericError(xmlGenericErrorContext, "\n");
2419 #endif
2420 		    *end = cur;
2421 		    *endindex = pos + stringlen;
2422 		    return(1);
2423 		} else {
2424 		    return(0);
2425 		}
2426 	    } else {
2427                 int sub = len - pos;
2428 		match = (!xmlStrncmp(&cur->content[pos], string, sub));
2429 		if (match) {
2430 #ifdef DEBUG_RANGES
2431 		    xmlGenericError(xmlGenericErrorContext,
2432 			    "found subrange %d bytes at index %d of ->",
2433 			    sub, pos + 1);
2434 		    xmlDebugDumpString(stdout, cur->content);
2435 		    xmlGenericError(xmlGenericErrorContext, "\n");
2436 #endif
2437                     string = &string[sub];
2438 		    stringlen -= sub;
2439 		} else {
2440 		    return(0);
2441 		}
2442 	    }
2443 	}
2444 	cur = xmlXPtrAdvanceNode(cur, NULL);
2445 	if (cur == NULL)
2446 	    return(0);
2447 	pos = 0;
2448     }
2449     return(1);
2450 }
2451 
2452 /**
2453  * xmlXPtrSearchString:
2454  * @string:  the string to search
2455  * @start:  the start textnode IN/OUT
2456  * @startindex:  the start index IN/OUT
2457  * @end:  the end textnode
2458  * @endindex:  the end index
2459  *
2460  * Search the next occurrence of @string within the document content
2461  * until the (@end, @endindex) point is reached
2462  *
2463  * Returns -1 in case of failure, 0 if not found, 1 if found in which case
2464  *            (@start, @startindex) will indicate the position of the beginning
2465  *            of the range and (@end, @endindex) will indicate the end
2466  *            of the range
2467  */
2468 static int
2469 xmlXPtrSearchString(const xmlChar *string, xmlNodePtr *start, int *startindex,
2470 	            xmlNodePtr *end, int *endindex) {
2471     xmlNodePtr cur;
2472     const xmlChar *str;
2473     int pos; /* 0 based */
2474     int len; /* in bytes */
2475     xmlChar first;
2476 
2477     if (string == NULL)
2478 	return(-1);
2479     if ((start == NULL) || (*start == NULL) ||
2480         ((*start)->type == XML_NAMESPACE_DECL) || (startindex == NULL))
2481 	return(-1);
2482     if ((end == NULL) || (endindex == NULL))
2483 	return(-1);
2484     cur = *start;
2485     pos = *startindex - 1;
2486     first = string[0];
2487 
2488     while (cur != NULL) {
2489 	if ((cur->type != XML_ELEMENT_NODE) && (cur->content != NULL)) {
2490 	    len = xmlStrlen(cur->content);
2491 	    while (pos <= len) {
2492 		if (first != 0) {
2493 		    str = xmlStrchr(&cur->content[pos], first);
2494 		    if (str != NULL) {
2495 			pos = (str - (xmlChar *)(cur->content));
2496 #ifdef DEBUG_RANGES
2497 			xmlGenericError(xmlGenericErrorContext,
2498 				"found '%c' at index %d of ->",
2499 				first, pos + 1);
2500 			xmlDebugDumpString(stdout, cur->content);
2501 			xmlGenericError(xmlGenericErrorContext, "\n");
2502 #endif
2503 			if (xmlXPtrMatchString(string, cur, pos + 1,
2504 					       end, endindex)) {
2505 			    *start = cur;
2506 			    *startindex = pos + 1;
2507 			    return(1);
2508 			}
2509 			pos++;
2510 		    } else {
2511 			pos = len + 1;
2512 		    }
2513 		} else {
2514 		    /*
2515 		     * An empty string is considered to match before each
2516 		     * character of the string-value and after the final
2517 		     * character.
2518 		     */
2519 #ifdef DEBUG_RANGES
2520 		    xmlGenericError(xmlGenericErrorContext,
2521 			    "found '' at index %d of ->",
2522 			    pos + 1);
2523 		    xmlDebugDumpString(stdout, cur->content);
2524 		    xmlGenericError(xmlGenericErrorContext, "\n");
2525 #endif
2526 		    *start = cur;
2527 		    *startindex = pos + 1;
2528 		    *end = cur;
2529 		    *endindex = pos + 1;
2530 		    return(1);
2531 		}
2532 	    }
2533 	}
2534 	if ((cur == *end) && (pos >= *endindex))
2535 	    return(0);
2536 	cur = xmlXPtrAdvanceNode(cur, NULL);
2537 	if (cur == NULL)
2538 	    return(0);
2539 	pos = 1;
2540     }
2541     return(0);
2542 }
2543 
2544 /**
2545  * xmlXPtrGetLastChar:
2546  * @node:  the node
2547  * @index:  the index
2548  *
2549  * Computes the point coordinates of the last char of this point
2550  *
2551  * Returns -1 in case of failure, 0 otherwise
2552  */
2553 static int
2554 xmlXPtrGetLastChar(xmlNodePtr *node, int *indx) {
2555     xmlNodePtr cur;
2556     int pos, len = 0;
2557 
2558     if ((node == NULL) || (*node == NULL) ||
2559         ((*node)->type == XML_NAMESPACE_DECL) || (indx == NULL))
2560 	return(-1);
2561     cur = *node;
2562     pos = *indx;
2563 
2564     if ((cur->type == XML_ELEMENT_NODE) ||
2565 	(cur->type == XML_DOCUMENT_NODE) ||
2566 	(cur->type == XML_HTML_DOCUMENT_NODE)) {
2567 	if (pos > 0) {
2568 	    cur = xmlXPtrGetNthChild(cur, pos);
2569 	}
2570     }
2571     while (cur != NULL) {
2572 	if (cur->last != NULL)
2573 	    cur = cur->last;
2574 	else if ((cur->type != XML_ELEMENT_NODE) &&
2575 	         (cur->content != NULL)) {
2576 	    len = xmlStrlen(cur->content);
2577 	    break;
2578 	} else {
2579 	    return(-1);
2580 	}
2581     }
2582     if (cur == NULL)
2583 	return(-1);
2584     *node = cur;
2585     *indx = len;
2586     return(0);
2587 }
2588 
2589 /**
2590  * xmlXPtrGetStartPoint:
2591  * @obj:  an range
2592  * @node:  the resulting node
2593  * @indx:  the resulting index
2594  *
2595  * read the object and return the start point coordinates.
2596  *
2597  * Returns -1 in case of failure, 0 otherwise
2598  */
2599 static int
2600 xmlXPtrGetStartPoint(xmlXPathObjectPtr obj, xmlNodePtr *node, int *indx) {
2601     if ((obj == NULL) || (node == NULL) || (indx == NULL))
2602 	return(-1);
2603 
2604     switch (obj->type) {
2605         case XPATH_POINT:
2606 	    *node = obj->user;
2607 	    if (obj->index <= 0)
2608 		*indx = 0;
2609 	    else
2610 		*indx = obj->index;
2611 	    return(0);
2612         case XPATH_RANGE:
2613 	    *node = obj->user;
2614 	    if (obj->index <= 0)
2615 		*indx = 0;
2616 	    else
2617 		*indx = obj->index;
2618 	    return(0);
2619 	default:
2620 	    break;
2621     }
2622     return(-1);
2623 }
2624 
2625 /**
2626  * xmlXPtrGetEndPoint:
2627  * @obj:  an range
2628  * @node:  the resulting node
2629  * @indx:  the resulting indx
2630  *
2631  * read the object and return the end point coordinates.
2632  *
2633  * Returns -1 in case of failure, 0 otherwise
2634  */
2635 static int
2636 xmlXPtrGetEndPoint(xmlXPathObjectPtr obj, xmlNodePtr *node, int *indx) {
2637     if ((obj == NULL) || (node == NULL) || (indx == NULL))
2638 	return(-1);
2639 
2640     switch (obj->type) {
2641         case XPATH_POINT:
2642 	    *node = obj->user;
2643 	    if (obj->index <= 0)
2644 		*indx = 0;
2645 	    else
2646 		*indx = obj->index;
2647 	    return(0);
2648         case XPATH_RANGE:
2649 	    *node = obj->user;
2650 	    if (obj->index <= 0)
2651 		*indx = 0;
2652 	    else
2653 		*indx = obj->index;
2654 	    return(0);
2655 	default:
2656 	    break;
2657     }
2658     return(-1);
2659 }
2660 
2661 /**
2662  * xmlXPtrStringRangeFunction:
2663  * @ctxt:  the XPointer Parser context
2664  * @nargs:  the number of args
2665  *
2666  * Function implementing the string-range() function
2667  * range as described in 5.4.2
2668  *
2669  * ------------------------------
2670  * [Definition: For each location in the location-set argument,
2671  * string-range returns a set of string ranges, a set of substrings in a
2672  * string. Specifically, the string-value of the location is searched for
2673  * substrings that match the string argument, and the resulting location-set
2674  * will contain a range location for each non-overlapping match.]
2675  * An empty string is considered to match before each character of the
2676  * string-value and after the final character. Whitespace in a string
2677  * is matched literally, with no normalization except that provided by
2678  * XML for line ends. The third argument gives the position of the first
2679  * character to be in the resulting range, relative to the start of the
2680  * match. The default value is 1, which makes the range start immediately
2681  * before the first character of the matched string. The fourth argument
2682  * gives the number of characters in the range; the default is that the
2683  * range extends to the end of the matched string.
2684  *
2685  * Element boundaries, as well as entire embedded nodes such as processing
2686  * instructions and comments, are ignored as defined in [XPath].
2687  *
2688  * If the string in the second argument is not found in the string-value
2689  * of the location, or if a value in the third or fourth argument indicates
2690  * a string that is beyond the beginning or end of the document, the
2691  * expression fails.
2692  *
2693  * The points of the range-locations in the returned location-set will
2694  * all be character points.
2695  * ------------------------------
2696  */
2697 static void
2698 xmlXPtrStringRangeFunction(xmlXPathParserContextPtr ctxt, int nargs) {
2699     int i, startindex, endindex = 0, fendindex;
2700     xmlNodePtr start, end = 0, fend;
2701     xmlXPathObjectPtr set;
2702     xmlLocationSetPtr oldset;
2703     xmlLocationSetPtr newset;
2704     xmlXPathObjectPtr string;
2705     xmlXPathObjectPtr position = NULL;
2706     xmlXPathObjectPtr number = NULL;
2707     int found, pos = 0, num = 0;
2708 
2709     /*
2710      * Grab the arguments
2711      */
2712     if ((nargs < 2) || (nargs > 4))
2713 	XP_ERROR(XPATH_INVALID_ARITY);
2714 
2715     if (nargs >= 4) {
2716 	CHECK_TYPE(XPATH_NUMBER);
2717 	number = valuePop(ctxt);
2718 	if (number != NULL)
2719 	    num = (int) number->floatval;
2720     }
2721     if (nargs >= 3) {
2722 	CHECK_TYPE(XPATH_NUMBER);
2723 	position = valuePop(ctxt);
2724 	if (position != NULL)
2725 	    pos = (int) position->floatval;
2726     }
2727     CHECK_TYPE(XPATH_STRING);
2728     string = valuePop(ctxt);
2729     if ((ctxt->value == NULL) ||
2730 	((ctxt->value->type != XPATH_LOCATIONSET) &&
2731 	 (ctxt->value->type != XPATH_NODESET)))
2732         XP_ERROR(XPATH_INVALID_TYPE)
2733 
2734     set = valuePop(ctxt);
2735     newset = xmlXPtrLocationSetCreate(NULL);
2736     if (newset == NULL) {
2737 	xmlXPathFreeObject(set);
2738         XP_ERROR(XPATH_MEMORY_ERROR);
2739     }
2740     if (set->nodesetval == NULL) {
2741         goto error;
2742     }
2743     if (set->type == XPATH_NODESET) {
2744 	xmlXPathObjectPtr tmp;
2745 
2746 	/*
2747 	 * First convert to a location set
2748 	 */
2749 	tmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);
2750 	xmlXPathFreeObject(set);
2751 	if (tmp == NULL)
2752 	     XP_ERROR(XPATH_MEMORY_ERROR)
2753 	set = tmp;
2754     }
2755     oldset = (xmlLocationSetPtr) set->user;
2756 
2757     /*
2758      * The loop is to search for each element in the location set
2759      * the list of location set corresponding to that search
2760      */
2761     for (i = 0;i < oldset->locNr;i++) {
2762 #ifdef DEBUG_RANGES
2763 	xmlXPathDebugDumpObject(stdout, oldset->locTab[i], 0);
2764 #endif
2765 
2766 	xmlXPtrGetStartPoint(oldset->locTab[i], &start, &startindex);
2767 	xmlXPtrGetEndPoint(oldset->locTab[i], &end, &endindex);
2768 	xmlXPtrAdvanceChar(&start, &startindex, 0);
2769 	xmlXPtrGetLastChar(&end, &endindex);
2770 
2771 #ifdef DEBUG_RANGES
2772 	xmlGenericError(xmlGenericErrorContext,
2773 		"from index %d of ->", startindex);
2774 	xmlDebugDumpString(stdout, start->content);
2775 	xmlGenericError(xmlGenericErrorContext, "\n");
2776 	xmlGenericError(xmlGenericErrorContext,
2777 		"to index %d of ->", endindex);
2778 	xmlDebugDumpString(stdout, end->content);
2779 	xmlGenericError(xmlGenericErrorContext, "\n");
2780 #endif
2781 	do {
2782             fend = end;
2783             fendindex = endindex;
2784 	    found = xmlXPtrSearchString(string->stringval, &start, &startindex,
2785 		                        &fend, &fendindex);
2786 	    if (found == 1) {
2787 		if (position == NULL) {
2788 		    xmlXPtrLocationSetAdd(newset,
2789 			 xmlXPtrNewRange(start, startindex, fend, fendindex));
2790 		} else if (xmlXPtrAdvanceChar(&start, &startindex,
2791 			                      pos - 1) == 0) {
2792 		    if ((number != NULL) && (num > 0)) {
2793 			int rindx;
2794 			xmlNodePtr rend;
2795 			rend = start;
2796 			rindx = startindex - 1;
2797 			if (xmlXPtrAdvanceChar(&rend, &rindx,
2798 				               num) == 0) {
2799 			    xmlXPtrLocationSetAdd(newset,
2800 					xmlXPtrNewRange(start, startindex,
2801 							rend, rindx));
2802 			}
2803 		    } else if ((number != NULL) && (num <= 0)) {
2804 			xmlXPtrLocationSetAdd(newset,
2805 				    xmlXPtrNewRange(start, startindex,
2806 						    start, startindex));
2807 		    } else {
2808 			xmlXPtrLocationSetAdd(newset,
2809 				    xmlXPtrNewRange(start, startindex,
2810 						    fend, fendindex));
2811 		    }
2812 		}
2813 		start = fend;
2814 		startindex = fendindex;
2815 		if (string->stringval[0] == 0)
2816 		    startindex++;
2817 	    }
2818 	} while (found == 1);
2819     }
2820 
2821     /*
2822      * Save the new value and cleanup
2823      */
2824 error:
2825     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2826     xmlXPathFreeObject(set);
2827     xmlXPathFreeObject(string);
2828     if (position) xmlXPathFreeObject(position);
2829     if (number) xmlXPathFreeObject(number);
2830 }
2831 
2832 /**
2833  * xmlXPtrEvalRangePredicate:
2834  * @ctxt:  the XPointer Parser context
2835  *
2836  *  [8]   Predicate ::=   '[' PredicateExpr ']'
2837  *  [9]   PredicateExpr ::=   Expr
2838  *
2839  * Evaluate a predicate as in xmlXPathEvalPredicate() but for
2840  * a Location Set instead of a node set
2841  */
2842 void
2843 xmlXPtrEvalRangePredicate(xmlXPathParserContextPtr ctxt) {
2844     const xmlChar *cur;
2845     xmlXPathObjectPtr res;
2846     xmlXPathObjectPtr obj, tmp;
2847     xmlLocationSetPtr newset = NULL;
2848     xmlLocationSetPtr oldset;
2849     int i;
2850 
2851     if (ctxt == NULL) return;
2852 
2853     SKIP_BLANKS;
2854     if (CUR != '[') {
2855 	XP_ERROR(XPATH_INVALID_PREDICATE_ERROR);
2856     }
2857     NEXT;
2858     SKIP_BLANKS;
2859 
2860     /*
2861      * Extract the old set, and then evaluate the result of the
2862      * expression for all the element in the set. use it to grow
2863      * up a new set.
2864      */
2865     CHECK_TYPE(XPATH_LOCATIONSET);
2866     obj = valuePop(ctxt);
2867     oldset = obj->user;
2868     ctxt->context->node = NULL;
2869 
2870     if ((oldset == NULL) || (oldset->locNr == 0)) {
2871 	ctxt->context->contextSize = 0;
2872 	ctxt->context->proximityPosition = 0;
2873 	xmlXPathEvalExpr(ctxt);
2874 	res = valuePop(ctxt);
2875 	if (res != NULL)
2876 	    xmlXPathFreeObject(res);
2877 	valuePush(ctxt, obj);
2878 	CHECK_ERROR;
2879     } else {
2880 	/*
2881 	 * Save the expression pointer since we will have to evaluate
2882 	 * it multiple times. Initialize the new set.
2883 	 */
2884         cur = ctxt->cur;
2885 	newset = xmlXPtrLocationSetCreate(NULL);
2886 
2887         for (i = 0; i < oldset->locNr; i++) {
2888 	    ctxt->cur = cur;
2889 
2890 	    /*
2891 	     * Run the evaluation with a node list made of a single item
2892 	     * in the nodeset.
2893 	     */
2894 	    ctxt->context->node = oldset->locTab[i]->user;
2895 	    tmp = xmlXPathNewNodeSet(ctxt->context->node);
2896 	    valuePush(ctxt, tmp);
2897 	    ctxt->context->contextSize = oldset->locNr;
2898 	    ctxt->context->proximityPosition = i + 1;
2899 
2900 	    xmlXPathEvalExpr(ctxt);
2901 	    CHECK_ERROR;
2902 
2903 	    /*
2904 	     * The result of the evaluation need to be tested to
2905 	     * decided whether the filter succeeded or not
2906 	     */
2907 	    res = valuePop(ctxt);
2908 	    if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
2909 	        xmlXPtrLocationSetAdd(newset,
2910 			xmlXPathObjectCopy(oldset->locTab[i]));
2911 	    }
2912 
2913 	    /*
2914 	     * Cleanup
2915 	     */
2916 	    if (res != NULL)
2917 		xmlXPathFreeObject(res);
2918 	    if (ctxt->value == tmp) {
2919 		res = valuePop(ctxt);
2920 		xmlXPathFreeObject(res);
2921 	    }
2922 
2923 	    ctxt->context->node = NULL;
2924 	}
2925 
2926 	/*
2927 	 * The result is used as the new evaluation set.
2928 	 */
2929 	xmlXPathFreeObject(obj);
2930 	ctxt->context->node = NULL;
2931 	ctxt->context->contextSize = -1;
2932 	ctxt->context->proximityPosition = -1;
2933 	valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2934     }
2935     if (CUR != ']') {
2936 	XP_ERROR(XPATH_INVALID_PREDICATE_ERROR);
2937     }
2938 
2939     NEXT;
2940     SKIP_BLANKS;
2941 }
2942 
2943 #define bottom_xpointer
2944 #include "elfgcchack.h"
2945 #endif
2946 
2947