use xmlXPathIsNaN() and xmlXPathIsInf() tag a potential threading problem.
[platform/upstream/libxslt.git] / libxslt / pattern.c
1 /*
2  * pattern.c: Implemetation of the template match compilation and lookup
3  *
4  * Reference:
5  *   http://www.w3.org/TR/1999/REC-xslt-19991116
6  *
7  * See Copyright for the status of this software.
8  *
9  * daniel@veillard.com
10  */
11
12 /*
13  * TODO: handle pathological cases like *[*[@a="b"]]
14  * TODO: detect [number] at compilation, optimize accordingly
15  */
16
17 #include "libxslt.h"
18
19 #include <string.h>
20
21 #include <libxml/xmlmemory.h>
22 #include <libxml/tree.h>
23 #include <libxml/valid.h>
24 #include <libxml/hash.h>
25 #include <libxml/xmlerror.h>
26 #include <libxml/parserInternals.h>
27 #include "xslt.h"
28 #include "xsltInternals.h"
29 #include "xsltutils.h"
30 #include "imports.h"
31 #include "templates.h"
32 #include "keys.h"
33 #include "pattern.h"
34
35 #ifdef WITH_XSLT_DEBUG
36 #define WITH_XSLT_DEBUG_PATTERN
37 #endif
38
39 /*
40  * Types are private:
41  */
42
43 typedef enum {
44     XSLT_OP_END=0,
45     XSLT_OP_ROOT,
46     XSLT_OP_ELEM,
47     XSLT_OP_CHILD,
48     XSLT_OP_ATTR,
49     XSLT_OP_PARENT,
50     XSLT_OP_ANCESTOR,
51     XSLT_OP_ID,
52     XSLT_OP_KEY,
53     XSLT_OP_NS,
54     XSLT_OP_ALL,
55     XSLT_OP_PI,
56     XSLT_OP_COMMENT,
57     XSLT_OP_TEXT,
58     XSLT_OP_NODE,
59     XSLT_OP_PREDICATE
60 } xsltOp;
61
62
63 typedef struct _xsltStepOp xsltStepOp;
64 typedef xsltStepOp *xsltStepOpPtr;
65 struct _xsltStepOp {
66     xsltOp op;
67     xmlChar *value;
68     xmlChar *value2;
69     xmlChar *value3;
70     xmlXPathCompExprPtr comp;
71     /*
72      * Optimisations for count
73      */
74     xmlNodePtr previous;
75     int        index;
76     int        len;
77 };
78
79 struct _xsltCompMatch {
80     struct _xsltCompMatch *next; /* siblings in the name hash */
81     float priority;              /* the priority */
82     const xmlChar *pattern;       /* the pattern */
83     const xmlChar *mode;         /* the mode */
84     const xmlChar *modeURI;      /* the mode URI */
85     xsltTemplatePtr template;    /* the associated template */
86
87     /* TODO fix the statically allocated size steps[] */
88     int nbStep;
89     int maxStep;
90     xmlNsPtr *nsList;           /* the namespaces in scope */
91     int nsNr;                   /* the number of namespaces in scope */
92     xsltStepOp steps[20];        /* ops for computation */
93 };
94
95 typedef struct _xsltParserContext xsltParserContext;
96 typedef xsltParserContext *xsltParserContextPtr;
97 struct _xsltParserContext {
98     const xmlChar *cur;                 /* the current char being parsed */
99     const xmlChar *base;                /* the full expression */
100     xmlDocPtr      doc;                 /* the source document */
101     xmlNodePtr    elem;                 /* the source element */
102     int error;                          /* error code */
103     xsltCompMatchPtr comp;              /* the result */
104 };
105
106 /************************************************************************
107  *                                                                      *
108  *                      Type functions                                  *
109  *                                                                      *
110  ************************************************************************/
111
112 /**
113  * xsltNewCompMatch:
114  *
115  * Create a new XSLT CompMatch
116  *
117  * Returns the newly allocated xsltCompMatchPtr or NULL in case of error
118  */
119 static xsltCompMatchPtr
120 xsltNewCompMatch(void) {
121     xsltCompMatchPtr cur;
122
123     cur = (xsltCompMatchPtr) xmlMalloc(sizeof(xsltCompMatch));
124     if (cur == NULL) {
125         xsltPrintErrorContext(NULL, NULL, NULL);
126         xsltGenericError(xsltGenericErrorContext,
127                 "xsltNewCompMatch : malloc failed\n");
128         return(NULL);
129     }
130     memset(cur, 0, sizeof(xsltCompMatch));
131     cur->maxStep = 20;
132     cur->nsNr = 0;
133     cur->nsList = NULL;
134     return(cur);
135 }
136
137 /**
138  * xsltFreeCompMatch:
139  * @comp:  an XSLT comp
140  *
141  * Free up the memory allocated by @comp
142  */
143 static void
144 xsltFreeCompMatch(xsltCompMatchPtr comp) {
145     xsltStepOpPtr op;
146     int i;
147
148     if (comp == NULL)
149         return;
150     if (comp->pattern != NULL)
151         xmlFree((xmlChar *)comp->pattern);
152     if (comp->mode != NULL)
153         xmlFree((xmlChar *)comp->mode);
154     if (comp->modeURI != NULL)
155         xmlFree((xmlChar *)comp->modeURI);
156     if (comp->nsList != NULL)
157         xmlFree(comp->nsList);
158     for (i = 0;i < comp->nbStep;i++) {
159         op = &comp->steps[i];
160         if (op->value != NULL)
161             xmlFree(op->value);
162         if (op->value2 != NULL)
163             xmlFree(op->value2);
164         if (op->value3 != NULL)
165             xmlFree(op->value3);
166         if (op->comp != NULL)
167             xmlXPathFreeCompExpr(op->comp);
168     }
169     memset(comp, -1, sizeof(xsltCompMatch));
170     xmlFree(comp);
171 }
172
173 /**
174  * xsltFreeCompMatchList:
175  * @comp:  an XSLT comp list
176  *
177  * Free up the memory allocated by all the elements of @comp
178  */
179 void
180 xsltFreeCompMatchList(xsltCompMatchPtr comp) {
181     xsltCompMatchPtr cur;
182
183     while (comp != NULL) {
184         cur = comp;
185         comp = comp->next;
186         xsltFreeCompMatch(cur);
187     }
188 }
189
190 /**
191  * xsltNewParserContext:
192  *
193  * Create a new XSLT ParserContext
194  *
195  * Returns the newly allocated xsltParserContextPtr or NULL in case of error
196  */
197 static xsltParserContextPtr
198 xsltNewParserContext(void) {
199     xsltParserContextPtr cur;
200
201     cur = (xsltParserContextPtr) xmlMalloc(sizeof(xsltParserContext));
202     if (cur == NULL) {
203         xsltPrintErrorContext(NULL, NULL, NULL);
204         xsltGenericError(xsltGenericErrorContext,
205                 "xsltNewParserContext : malloc failed\n");
206         return(NULL);
207     }
208     memset(cur, 0, sizeof(xsltParserContext));
209     return(cur);
210 }
211
212 /**
213  * xsltFreeParserContext:
214  * @ctxt:  an XSLT parser context
215  *
216  * Free up the memory allocated by @ctxt
217  */
218 static void
219 xsltFreeParserContext(xsltParserContextPtr ctxt) {
220     if (ctxt == NULL)
221         return;
222     memset(ctxt, -1, sizeof(xsltParserContext));
223     xmlFree(ctxt);
224 }
225
226 /**
227  * xsltCompMatchAdd:
228  * @comp:  the compiled match expression
229  * @op:  an op
230  * @value:  the first value
231  * @value2:  the second value
232  *
233  * Add an step to an XSLT Compiled Match
234  *
235  * Returns -1 in case of failure, 0 otherwise.
236  */
237 static int
238 xsltCompMatchAdd(xsltCompMatchPtr comp, xsltOp op, xmlChar *value,
239                  xmlChar *value2) {
240     if (comp->nbStep >= 20) {
241         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
242         xsltGenericError(xsltGenericErrorContext,
243                 "xsltCompMatchAdd: overflow\n");
244         return(-1);
245     }
246     comp->steps[comp->nbStep].op = op;
247     comp->steps[comp->nbStep].value = value;
248     comp->steps[comp->nbStep].value2 = value2;
249     comp->nbStep++;
250     return(0);
251 }
252
253 /**
254  * xsltSwapTopCompMatch:
255  * @comp:  the compiled match expression
256  *
257  * reverse the two top steps.
258  */
259 static void
260 xsltSwapTopCompMatch(xsltCompMatchPtr comp) {
261     int i;
262     int j = comp->nbStep - 1;
263
264     if (j > 0) {
265         register xmlChar *tmp;
266         register xsltOp op;
267         i = j - 1;
268         tmp = comp->steps[i].value;
269         comp->steps[i].value = comp->steps[j].value;
270         comp->steps[j].value = tmp;
271         tmp = comp->steps[i].value2;
272         comp->steps[i].value2 = comp->steps[j].value2;
273         comp->steps[j].value2 = tmp;
274         op = comp->steps[i].op;
275         comp->steps[i].op = comp->steps[j].op;
276         comp->steps[j].op = op;
277     }
278 }
279
280 /**
281  * xsltReverseCompMatch:
282  * @comp:  the compiled match expression
283  *
284  * reverse all the stack of expressions
285  */
286 static void
287 xsltReverseCompMatch(xsltCompMatchPtr comp) {
288     int i = 0;
289     int j = comp->nbStep - 1;
290
291     while (j > i) {
292         register xmlChar *tmp;
293         register xsltOp op;
294         tmp = comp->steps[i].value;
295         comp->steps[i].value = comp->steps[j].value;
296         comp->steps[j].value = tmp;
297         tmp = comp->steps[i].value2;
298         comp->steps[i].value2 = comp->steps[j].value2;
299         comp->steps[j].value2 = tmp;
300         op = comp->steps[i].op;
301         comp->steps[i].op = comp->steps[j].op;
302         comp->steps[j].op = op;
303         j--;
304         i++;
305     }
306     comp->steps[comp->nbStep++].op = XSLT_OP_END;
307 }
308
309 /**
310  * xsltCleanupCompMatch:
311  * @comp:  the compiled match expression
312  *
313  * remove all computation state from the pattern
314  */
315 static void
316 xsltCleanupCompMatch(xsltCompMatchPtr comp) {
317     int i;
318     
319     for (i = 0;i < comp->nbStep;i++) {
320         comp->steps[i].previous = NULL;
321     }
322 }
323
324 /************************************************************************
325  *                                                                      *
326  *              The interpreter for the precompiled patterns            *
327  *                                                                      *
328  ************************************************************************/
329
330 /**
331  * xsltTestCompMatch:
332  * @ctxt:  a XSLT process context
333  * @comp: the precompiled pattern
334  * @node: a node
335  * @mode:  the mode name or NULL
336  * @modeURI:  the mode URI or NULL
337  *
338  * Test wether the node matches the pattern
339  *
340  * Returns 1 if it matches, 0 if it doesn't and -1 in case of failure
341  */
342 static int
343 xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp,
344                   xmlNodePtr node, const xmlChar *mode,
345                   const xmlChar *modeURI) {
346     int i;
347     xsltStepOpPtr step, select = NULL;
348
349     if ((comp == NULL) || (node == NULL) || (ctxt == NULL)) {
350         xsltPrintErrorContext(ctxt, NULL, node);
351         xsltGenericError(xsltGenericErrorContext,
352                 "xsltTestCompMatch: null arg\n");
353         return(-1);
354     }
355     if (mode != NULL) {
356         if (comp->mode == NULL)
357             return(0);
358         if ((comp->mode != mode) && (!xmlStrEqual(comp->mode, mode)))
359             return(0);
360     } else {
361         if (comp->mode != NULL)
362             return(0);
363     }
364     if (modeURI != NULL) {
365         if (comp->modeURI == NULL)
366             return(0);
367         if ((comp->modeURI != modeURI) &&
368             (!xmlStrEqual(comp->modeURI, modeURI)))
369             return(0);
370     } else {
371         if (comp->modeURI != NULL)
372             return(0);
373     }
374     for (i = 0;i < comp->nbStep;i++) {
375         step = &comp->steps[i];
376         if (step->op != XSLT_OP_PREDICATE)
377             select = step;
378         switch (step->op) {
379             case XSLT_OP_END:
380                 return(1);
381             case XSLT_OP_ROOT:
382                 if ((node->type == XML_DOCUMENT_NODE) ||
383 #ifdef LIBXML_DOCB_ENABLED
384                     (node->type != XML_DOCB_DOCUMENT_NODE) ||
385 #endif
386                     (node->type == XML_HTML_DOCUMENT_NODE))
387                     continue;
388                 return(0);
389             case XSLT_OP_ELEM:
390                 if (node->type != XML_ELEMENT_NODE)
391                     return(0);
392                 if (step->value == NULL)
393                     continue;
394                 if (!xmlStrEqual(step->value, node->name))
395                     return(0);
396
397                 /* Namespace test */
398                 if (node->ns == NULL) {
399                     if (step->value2 != NULL)
400                         return(0);
401                 } else if (node->ns->href != NULL) {
402                     if (step->value2 == NULL)
403                         return(0);
404                     if (!xmlStrEqual(step->value2, node->ns->href))
405                         return(0);
406                 }
407                 continue;
408             case XSLT_OP_CHILD: {
409                 xmlNodePtr lst;
410
411                 if ((node->type != XML_ELEMENT_NODE) &&
412                     (node->type != XML_DOCUMENT_NODE) &&
413 #ifdef LIBXML_DOCB_ENABLED
414                     (node->type != XML_DOCB_DOCUMENT_NODE) &&
415 #endif
416                     (node->type != XML_HTML_DOCUMENT_NODE))
417                     return(0);
418
419                 lst = node->children;
420
421                 if (step->value != NULL) {
422                     while (lst != NULL) {
423                         if ((lst->type == XML_ELEMENT_NODE) &&
424                             (xmlStrEqual(step->value, lst->name)))
425                             break;
426                         lst = lst->next;
427                     }
428                     if (lst != NULL)
429                         continue;
430                 }
431                 return(0);
432             }
433             case XSLT_OP_ATTR:
434                 if (node->type != XML_ATTRIBUTE_NODE)
435                     return(0);
436                 if (step->value == NULL)
437                     continue;
438                 if (!xmlStrEqual(step->value, node->name))
439                     return(0);
440
441                 /* Namespace test */
442                 if (node->ns == NULL) {
443                     if (step->value2 != NULL)
444                         return(0);
445                 } else if (node->ns->href != NULL) {
446                     if (step->value2 == NULL)
447                         return(0);
448                     if (!xmlStrEqual(step->value2, node->ns->href))
449                         return(0);
450                 }
451                 continue;
452             case XSLT_OP_PARENT:
453                 if ((node->type != XML_ELEMENT_NODE) &&
454                     (node->type != XML_ATTRIBUTE_NODE))
455                     return(0);
456                 node = node->parent;
457                 if (node == NULL)
458                     return(0);
459                 if (step->value == NULL)
460                     continue;
461                 if (!xmlStrEqual(step->value, node->name))
462                     return(0);
463                 /* Namespace test */
464                 if (node->ns == NULL) {
465                     if (step->value2 != NULL)
466                         return(0);
467                 } else if (node->ns->href != NULL) {
468                     if (step->value2 == NULL)
469                         return(0);
470                     if (!xmlStrEqual(step->value2, node->ns->href))
471                         return(0);
472                 }
473                 continue;
474             case XSLT_OP_ANCESTOR:
475                 /* TODO: implement coalescing of ANCESTOR/NODE ops */
476                 if (step->value == NULL) {
477                     i++;
478                     step = &comp->steps[i];
479                     if (step->op == XSLT_OP_ROOT)
480                         return(1);
481                     if (step->op != XSLT_OP_ELEM)
482                         return(0);
483                     if (step->value == NULL)
484                         return(-1);
485                 }
486                 if (node == NULL)
487                     return(0);
488                 node = node->parent;
489                 while (node != NULL) {
490                     if (node == NULL)
491                         return(0);
492                     if (xmlStrEqual(step->value, node->name)) {
493                         /* Namespace test */
494                         if (node->ns == NULL) {
495                             if (step->value2 == NULL)
496                                 break;
497                         } else if (node->ns->href != NULL) {
498                             if ((step->value2 != NULL) &&
499                                 (xmlStrEqual(step->value2, node->ns->href)))
500                                 break;
501                         }
502                     }
503                     node = node->parent;
504                 }
505                 if (node == NULL)
506                     return(0);
507                 continue;
508             case XSLT_OP_ID: {
509                 /* TODO Handle IDs decently, must be done differently */
510                 xmlAttrPtr id;
511
512                 if (node->type != XML_ELEMENT_NODE)
513                     return(0);
514
515                 id = xmlGetID(node->doc, step->value);
516                 if ((id == NULL) || (id->parent != node))
517                     return(0);
518                 break;
519             }
520             case XSLT_OP_KEY: {
521                 xmlNodeSetPtr list;
522                 int indx;
523
524                 list = xsltGetKey(ctxt, step->value,
525                                   step->value3, step->value2);
526                 if (list == NULL)
527                     return(0);
528                 for (indx = 0;indx < list->nodeNr;indx++)
529                     if (list->nodeTab[indx] == node)
530                         break;
531                 if (indx >= list->nodeNr)
532                     return(0);
533                 break;
534             }
535             case XSLT_OP_NS:
536                 if (node->type != XML_ELEMENT_NODE)
537                     return(0);
538                 if (node->ns == NULL) {
539                     if (step->value != NULL)
540                         return(0);
541                 } else if (node->ns->href != NULL) {
542                     if (step->value == NULL)
543                         return(0);
544                     if (!xmlStrEqual(step->value, node->ns->href))
545                         return(0);
546                 }
547                 break;
548             case XSLT_OP_ALL:
549                 if (node->type != XML_ELEMENT_NODE)
550                     return(0);
551                 break;
552             case XSLT_OP_PREDICATE: {
553                 xmlNodePtr oldNode;
554                 int oldCS, oldCP;
555                 int pos = 0, len = 0;
556                 /*
557                  * Depending on the last selection, one may need to
558                  * recompute contextSize and proximityPosition.
559                  *
560                  * TODO: make this thread safe !
561                  */
562                 oldCS = ctxt->xpathCtxt->contextSize;
563                 oldCP = ctxt->xpathCtxt->proximityPosition;
564                 if ((select != NULL) &&
565                     (select->op == XSLT_OP_ELEM) &&
566                     (select->value != NULL) &&
567                     (node->type == XML_ELEMENT_NODE) &&
568                     (node->parent != NULL)) {
569
570                     if ((select->previous != NULL) &&
571                         (select->previous->parent == node->parent)) {
572                         /*
573                          * just walk back to adjust the index
574                          */
575                         int indx = 0;
576                         xmlNodePtr sibling = node;
577
578                         while (sibling != NULL) {
579                             if (sibling == select->previous)
580                                 break;
581                             if (xmlStrEqual(node->name, sibling->name)) {
582                                 if ((select->value2 == NULL) ||
583                                     ((sibling->ns != NULL) &&
584                                      (xmlStrEqual(select->value2,
585                                                   sibling->ns->href))))
586                                     indx++;
587                             }
588                             sibling = sibling->prev;
589                         }
590                         if (sibling == NULL) {
591                             /* hum going backward in document order ... */
592                             indx = 0;
593                             sibling = node;
594                             while (sibling != NULL) {
595                                 if (sibling == select->previous)
596                                     break;
597                                 if ((select->value2 == NULL) ||
598                                     ((sibling->ns != NULL) &&
599                                      (xmlStrEqual(select->value2,
600                                                   sibling->ns->href))))
601                                     indx--;
602                                 sibling = sibling->next;
603                             }
604                         }
605                         if (sibling != NULL) {
606                             pos = select->index + indx;
607                             len = select->len;
608                             select->previous = node;
609                             select->index = pos;
610                         } else
611                             pos = 0;
612                     } else {
613                         /*
614                          * recompute the index
615                          */
616                         xmlNodePtr siblings = node->parent->children;
617
618                         while (siblings != NULL) {
619                             if (siblings->type == XML_ELEMENT_NODE) {
620                                 if (siblings == node) {
621                                     len++;
622                                     pos = len;
623                                 } else if (xmlStrEqual(node->name,
624                                            siblings->name)) {
625                                     if ((select->value2 == NULL) ||
626                                         ((siblings->ns != NULL) &&
627                                          (xmlStrEqual(select->value2,
628                                                       siblings->ns->href))))
629                                         len++;
630                                 }
631                             }
632                             siblings = siblings->next;
633                         }
634                     }
635                     if (pos != 0) {
636                         ctxt->xpathCtxt->contextSize = len;
637                         ctxt->xpathCtxt->proximityPosition = pos;
638                         select->previous = node;
639                         select->index = pos;
640                         select->len = len;
641                     }
642                 } else if ((select != NULL) && (select->op == XSLT_OP_ALL) &&
643                            (node->type == XML_ELEMENT_NODE)) {
644                     if ((select->previous != NULL) &&
645                         (select->previous->parent == node->parent)) {
646                         /*
647                          * just walk back to adjust the index
648                          */
649                         int indx = 0;
650                         xmlNodePtr sibling = node;
651
652                         while (sibling != NULL) {
653                             if (sibling == select->previous)
654                                 break;
655                             if (sibling->type == XML_ELEMENT_NODE)
656                                 indx++;
657                             sibling = sibling->prev;
658                         }
659                         if (sibling == NULL) {
660                             /* hum going backward in document order ... */
661                             indx = 0;
662                             sibling = node;
663                             while (sibling != NULL) {
664                                 if (sibling == select->previous)
665                                     break;
666                                 if (sibling->type == XML_ELEMENT_NODE)
667                                     indx--;
668                                 sibling = sibling->next;
669                             }
670                         }
671                         if (sibling != NULL) {
672                             pos = select->index + indx;
673                             len = select->len;
674                             select->previous = node;
675                             select->index = pos;
676                         } else
677                             pos = 0;
678                     } else {
679                         /*
680                          * recompute the index
681                          */
682                         xmlNodePtr siblings = node->parent->children;
683
684                         while (siblings != NULL) {
685                             if (siblings->type == XML_ELEMENT_NODE) {
686                                 len++;
687                                 if (siblings == node) {
688                                     pos = len;
689                                 }
690                             }
691                             siblings = siblings->next;
692                         }
693                     }
694                     if (pos != 0) {
695                         ctxt->xpathCtxt->contextSize = len;
696                         ctxt->xpathCtxt->proximityPosition = pos;
697                         select->previous = node;
698                         select->index = pos;
699                         select->len = len;
700                     }
701                 }
702                 oldNode = ctxt->node;
703                 ctxt->node = node;
704
705                 if (step->value == NULL)
706                     goto wrong_index;
707
708                 if (step->comp == NULL) {
709                     step->comp = xmlXPathCompile(step->value);
710                     if (step->comp == NULL)
711                         goto wrong_index;
712                 }
713                 if (comp->nsList == NULL) {
714                     int j = 0;
715
716                     comp->nsList = xmlGetNsList(node->doc, node);
717                     if (comp->nsList != NULL) {
718                         while (comp->nsList[j] != NULL)
719                             j++;
720                     }
721                     comp->nsNr = j;
722                 }
723                 if (!xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList,
724                                             comp->nsNr))
725                     goto wrong_index;
726
727                 if (pos != 0) {
728                     ctxt->xpathCtxt->contextSize = oldCS;
729                     ctxt->xpathCtxt->proximityPosition = oldCP;
730                 }
731                 ctxt->node = oldNode;
732                 break;
733 wrong_index:
734                 if (pos != 0) {
735                     ctxt->xpathCtxt->contextSize = oldCS;
736                     ctxt->xpathCtxt->proximityPosition = oldCP;
737                 }
738                 ctxt->node = oldNode;
739                 return(0);
740             }
741             case XSLT_OP_PI:
742                 if (node->type != XML_PI_NODE)
743                     return(0);
744                 if (step->value != NULL) {
745                     if (!xmlStrEqual(step->value, node->name))
746                         return(0);
747                 }
748                 break;
749             case XSLT_OP_COMMENT:
750                 if (node->type != XML_COMMENT_NODE)
751                     return(0);
752                 break;
753             case XSLT_OP_TEXT:
754                 if ((node->type != XML_TEXT_NODE) &&
755                     (node->type != XML_CDATA_SECTION_NODE))
756                     return(0);
757                 break;
758             case XSLT_OP_NODE:
759                 switch (node->type) {
760                     case XML_DOCUMENT_NODE:
761                     case XML_HTML_DOCUMENT_NODE:
762                     case XML_ELEMENT_NODE:
763                     case XML_CDATA_SECTION_NODE:
764                     case XML_PI_NODE:
765                     case XML_COMMENT_NODE:
766                     case XML_TEXT_NODE:
767                     case XML_ATTRIBUTE_NODE:
768                         break;
769                     default:
770                         return(0);
771                 }
772                 break;
773         }
774     }
775     return(1);
776 }
777
778 /**
779  * xsltTestCompMatchList:
780  * @ctxt:  a XSLT process context
781  * @node: a node
782  * @comp: the precompiled pattern list
783  *
784  * Test wether the node matches one of the patterns in the list
785  *
786  * Returns 1 if it matches, 0 if it doesn't and -1 in case of failure
787  */
788 int
789 xsltTestCompMatchList(xsltTransformContextPtr ctxt, xmlNodePtr node,
790                       xsltCompMatchPtr comp) {
791     int ret;
792
793     if ((ctxt == NULL) || (node == NULL))
794         return(-1);
795     while (comp != NULL) {
796         ret = xsltTestCompMatch(ctxt, comp, node, NULL, NULL);
797         if (ret == 1)
798             return(1);
799         comp = comp->next;
800     }
801     return(0);
802 }
803
804 /************************************************************************
805  *                                                                      *
806  *                      Dedicated parser for templates                  *
807  *                                                                      *
808  ************************************************************************/
809
810 #define CUR (*ctxt->cur)
811 #define SKIP(val) ctxt->cur += (val)
812 #define NXT(val) ctxt->cur[(val)]
813 #define CUR_PTR ctxt->cur
814
815 #define SKIP_BLANKS                                                     \
816     while (IS_BLANK(CUR)) NEXT
817
818 #define CURRENT (*ctxt->cur)
819 #define NEXT ((*ctxt->cur) ?  ctxt->cur++: ctxt->cur)
820
821
822 #define PUSH(op, val, val2)                                             \
823     if (xsltCompMatchAdd(ctxt->comp, (op), (val), (val2))) goto error;
824
825 #define SWAP()                                          \
826     xsltSwapTopCompMatch(ctxt->comp);
827
828 #define XSLT_ERROR(X)                                                   \
829     { xsltError(ctxt, __FILE__, __LINE__, X);                   \
830       ctxt->error = (X); return; }
831
832 #define XSLT_ERROR0(X)                                                  \
833     { xsltError(ctxt, __FILE__, __LINE__, X);                   \
834       ctxt->error = (X); return(0); }
835
836 /**
837  * xsltScanLiteral:
838  * @ctxt:  the XPath Parser context
839  *
840  * Parse an XPath Litteral:
841  *
842  * [29] Literal ::= '"' [^"]* '"'
843  *                | "'" [^']* "'"
844  *
845  * Returns the Literal parsed or NULL
846  */
847
848 static xmlChar *
849 xsltScanLiteral(xsltParserContextPtr ctxt) {
850     const xmlChar *q;
851     xmlChar *ret = NULL;
852
853     SKIP_BLANKS;
854     if (CUR == '"') {
855         NEXT;
856         q = CUR_PTR;
857         while ((IS_CHAR(CUR)) && (CUR != '"'))
858             NEXT;
859         if (!IS_CHAR(CUR)) {
860             /* XP_ERROR(XPATH_UNFINISHED_LITERAL_ERROR); */
861             ctxt->error = 1;
862             return(NULL);
863         } else {
864             ret = xmlStrndup(q, CUR_PTR - q);
865             NEXT;
866         }
867     } else if (CUR == '\'') {
868         NEXT;
869         q = CUR_PTR;
870         while ((IS_CHAR(CUR)) && (CUR != '\''))
871             NEXT;
872         if (!IS_CHAR(CUR)) {
873             /* XP_ERROR(XPATH_UNFINISHED_LITERAL_ERROR); */
874             ctxt->error = 1;
875             return(NULL);
876         } else {
877             ret = xmlStrndup(q, CUR_PTR - q);
878             NEXT;
879         }
880     } else {
881         /* XP_ERROR(XPATH_START_LITERAL_ERROR); */
882         ctxt->error = 1;
883         return(NULL);
884     }
885     return(ret);
886 }
887
888 /**
889  * xsltScanName:
890  * @ctxt:  the XPath Parser context
891  *
892  * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | 
893  *                  CombiningChar | Extender
894  *
895  * [5] Name ::= (Letter | '_' | ':') (NameChar)*
896  *
897  * [6] Names ::= Name (S Name)*
898  *
899  * Returns the Name parsed or NULL
900  */
901
902 static xmlChar *
903 xsltScanName(xsltParserContextPtr ctxt) {
904     xmlChar buf[XML_MAX_NAMELEN];
905     int len = 0;
906
907     SKIP_BLANKS;
908     if (!IS_LETTER(CUR) && (CUR != '_') &&
909         (CUR != ':')) {
910         return(NULL);
911     }
912
913     while ((IS_LETTER(NXT(len))) || (IS_DIGIT(NXT(len))) ||
914            (NXT(len) == '.') || (NXT(len) == '-') ||
915            (NXT(len) == '_') || 
916            (IS_COMBINING(NXT(len))) ||
917            (IS_EXTENDER(NXT(len)))) {
918         buf[len] = NXT(len);
919         len++;
920         if (len >= XML_MAX_NAMELEN) {
921             xmlGenericError(xmlGenericErrorContext, 
922                "xsltScanName: reached XML_MAX_NAMELEN limit\n");
923             while ((IS_LETTER(NXT(len))) || (IS_DIGIT(NXT(len))) ||
924                    (NXT(len) == '.') || (NXT(len) == '-') ||
925                    (NXT(len) == '_') || (NXT(len) == ':') || 
926                    (IS_COMBINING(NXT(len))) ||
927                    (IS_EXTENDER(NXT(len))))
928                  len++;
929             break;
930         }
931     }
932     SKIP(len);
933     return(xmlStrndup(buf, len));
934 }
935
936 /**
937  * xsltScanNCName:
938  * @ctxt:  the XPath Parser context
939  *
940  * Parses a non qualified name
941  *
942  * Returns the Name parsed or NULL
943  */
944
945 static xmlChar *
946 xsltScanNCName(xsltParserContextPtr ctxt) {
947     xmlChar buf[XML_MAX_NAMELEN];
948     int len = 0;
949
950     SKIP_BLANKS;
951     if (!IS_LETTER(CUR) && (CUR != '_')) {
952         return(NULL);
953     }
954
955     while ((IS_LETTER(NXT(len))) || (IS_DIGIT(NXT(len))) ||
956            (NXT(len) == '.') || (NXT(len) == '-') ||
957            (NXT(len) == '_') ||
958            (IS_COMBINING(NXT(len))) ||
959            (IS_EXTENDER(NXT(len)))) {
960         buf[len] = NXT(len);
961         len++;
962         if (len >= XML_MAX_NAMELEN) {
963             xmlGenericError(xmlGenericErrorContext, 
964                "xsltScanNCName: reached XML_MAX_NAMELEN limit\n");
965             while ((IS_LETTER(NXT(len))) || (IS_DIGIT(NXT(len))) ||
966                    (NXT(len) == '.') || (NXT(len) == '-') ||
967                    (NXT(len) == '_') ||
968                    (IS_COMBINING(NXT(len))) ||
969                    (IS_EXTENDER(NXT(len))))
970                  len++;
971             break;
972         }
973     }
974     SKIP(len);
975     return(xmlStrndup(buf, len));
976 }
977
978 /**
979  * xsltScanQName:
980  * @ctxt:  the XPath Parser context
981  * @prefix:  the place to store the prefix
982  *
983  * Parse a qualified name
984  *
985  * Returns the Name parsed or NULL
986  */
987
988 static xmlChar *
989 xsltScanQName(xsltParserContextPtr ctxt, xmlChar **prefix) {
990     xmlChar *ret = NULL;
991
992     *prefix = NULL;
993     ret = xsltScanNCName(ctxt);
994     if (CUR == ':') {
995         *prefix = ret;
996         NEXT;
997         ret = xsltScanNCName(ctxt);
998     }
999     return(ret);
1000 }
1001
1002 /*
1003  * xsltCompileIdKeyPattern:
1004  * @ctxt:  the compilation context
1005  * @name:  a preparsed name
1006  * @aid:  whether id/key are allowed there
1007  *
1008  * Compile the XSLT LocationIdKeyPattern
1009  * [3] IdKeyPattern ::= 'id' '(' Literal ')'
1010  *                    | 'key' '(' Literal ',' Literal ')'
1011  *
1012  * also handle NodeType and PI from:
1013  *
1014  * [7]  NodeTest ::= NameTest
1015  *                 | NodeType '(' ')'
1016  *                 | 'processing-instruction' '(' Literal ')'
1017  */
1018 static void
1019 xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name, int aid) {
1020     xmlChar *lit = NULL;
1021     xmlChar *lit2 = NULL;
1022
1023     if (CUR != '(') {
1024         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1025         xsltGenericError(xsltGenericErrorContext,
1026                 "xsltCompileIdKeyPattern : ( expected\n");
1027         ctxt->error = 1;
1028         return;
1029     }
1030     if ((aid) && (xmlStrEqual(name, (const xmlChar *)"id"))) {
1031         NEXT;
1032         SKIP_BLANKS;
1033         lit = xsltScanLiteral(ctxt);
1034         if (ctxt->error)
1035             return;
1036         SKIP_BLANKS;
1037         if (CUR != ')') {
1038             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1039             xsltGenericError(xsltGenericErrorContext,
1040                     "xsltCompileIdKeyPattern : ) expected\n");
1041             ctxt->error = 1;
1042             return;
1043         }
1044         NEXT;
1045         PUSH(XSLT_OP_ID, lit, NULL);
1046     } else if ((aid) && (xmlStrEqual(name, (const xmlChar *)"key"))) {
1047         NEXT;
1048         SKIP_BLANKS;
1049         lit = xsltScanLiteral(ctxt);
1050         if (ctxt->error)
1051             return;
1052         SKIP_BLANKS;
1053         if (CUR != ',') {
1054             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1055             xsltGenericError(xsltGenericErrorContext,
1056                     "xsltCompileIdKeyPattern : , expected\n");
1057             ctxt->error = 1;
1058             return;
1059         }
1060         NEXT;
1061         SKIP_BLANKS;
1062         lit2 = xsltScanLiteral(ctxt);
1063         if (ctxt->error)
1064             return;
1065         SKIP_BLANKS;
1066         if (CUR != ')') {
1067             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1068             xsltGenericError(xsltGenericErrorContext,
1069                     "xsltCompileIdKeyPattern : ) expected\n");
1070             ctxt->error = 1;
1071             return;
1072         }
1073         NEXT;
1074         /* TODO: support namespace in keys */
1075         PUSH(XSLT_OP_KEY, lit, lit2);
1076     } else if (xmlStrEqual(name, (const xmlChar *)"processing-instruction")) {
1077         NEXT;
1078         SKIP_BLANKS;
1079         if (CUR != ')') {
1080             lit = xsltScanLiteral(ctxt);
1081             if (ctxt->error)
1082                 return;
1083             SKIP_BLANKS;
1084             if (CUR != ')') {
1085                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1086                 xsltGenericError(xsltGenericErrorContext,
1087                         "xsltCompileIdKeyPattern : ) expected\n");
1088                 ctxt->error = 1;
1089                 return;
1090             }
1091         }
1092         NEXT;
1093         PUSH(XSLT_OP_PI, lit, NULL);
1094     } else if (xmlStrEqual(name, (const xmlChar *)"text")) {
1095         NEXT;
1096         SKIP_BLANKS;
1097         if (CUR != ')') {
1098             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1099             xsltGenericError(xsltGenericErrorContext,
1100                     "xsltCompileIdKeyPattern : ) expected\n");
1101             ctxt->error = 1;
1102             return;
1103         }
1104         NEXT;
1105         PUSH(XSLT_OP_TEXT, NULL, NULL);
1106     } else if (xmlStrEqual(name, (const xmlChar *)"comment")) {
1107         NEXT;
1108         SKIP_BLANKS;
1109         if (CUR != ')') {
1110             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1111             xsltGenericError(xsltGenericErrorContext,
1112                     "xsltCompileIdKeyPattern : ) expected\n");
1113             ctxt->error = 1;
1114             return;
1115         }
1116         NEXT;
1117         PUSH(XSLT_OP_COMMENT, NULL, NULL);
1118     } else if (xmlStrEqual(name, (const xmlChar *)"node")) {
1119         NEXT;
1120         SKIP_BLANKS;
1121         if (CUR != ')') {
1122             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1123             xsltGenericError(xsltGenericErrorContext,
1124                     "xsltCompileIdKeyPattern : ) expected\n");
1125             ctxt->error = 1;
1126             return;
1127         }
1128         NEXT;
1129         PUSH(XSLT_OP_NODE, NULL, NULL);
1130     } else if (aid) {
1131         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1132         xsltGenericError(xsltGenericErrorContext,
1133             "xsltCompileIdKeyPattern : expecting 'key' or 'id' or node type\n");
1134         ctxt->error = 1;
1135         return;
1136     } else {
1137         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1138         xsltGenericError(xsltGenericErrorContext,
1139             "xsltCompileIdKeyPattern : node type\n");
1140         ctxt->error = 1;
1141         return;
1142     }
1143 error:
1144     if (name != NULL)
1145         xmlFree(name);
1146 }
1147
1148 /**
1149  * xsltCompileStepPattern:
1150  * @ctxt:  the compilation context
1151  * @token:  a posible precompiled name
1152  *
1153  * Compile the XSLT StepPattern and generates a precompiled
1154  * form suitable for fast matching.
1155  *
1156  * [5] StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate* 
1157  * [6] ChildOrAttributeAxisSpecifier ::= AbbreviatedAxisSpecifier
1158  *                                     | ('child' | 'attribute') '::'
1159  * from XPath
1160  * [7]  NodeTest ::= NameTest
1161  *                 | NodeType '(' ')'
1162  *                 | 'processing-instruction' '(' Literal ')'
1163  * [8] Predicate ::= '[' PredicateExpr ']'
1164  * [9] PredicateExpr ::= Expr
1165  * [13] AbbreviatedAxisSpecifier ::= '@'?
1166  * [37] NameTest ::= '*' | NCName ':' '*' | QName
1167  */
1168
1169 static void
1170 xsltCompileStepPattern(xsltParserContextPtr ctxt, xmlChar *token) {
1171     xmlChar *name = NULL;
1172     const xmlChar *URI = NULL;
1173     xmlChar *URL = NULL;
1174     int level;
1175
1176     SKIP_BLANKS;
1177     if ((token == NULL) && (CUR == '@')) {
1178         xmlChar *prefix = NULL;
1179
1180         NEXT;
1181         if (CUR == '*') {
1182             NEXT;
1183             PUSH(XSLT_OP_ATTR, NULL, NULL);
1184             return;
1185         }
1186         token = xsltScanQName(ctxt, &prefix);
1187         if (prefix != NULL) {
1188             xmlNsPtr ns;
1189
1190             ns = xmlSearchNs(ctxt->doc, ctxt->elem, prefix);
1191             if (ns == NULL) {
1192                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1193                 xsltGenericError(xsltGenericErrorContext,
1194                 "xsltCompileStepPattern : no namespace bound to prefix %s\n",
1195                                  prefix);
1196             } else {
1197                 URL = xmlStrdup(ns->href);
1198             }
1199             xmlFree(prefix);
1200         }
1201         if (token == NULL) {
1202             if (CUR == '*') {
1203                 NEXT;
1204                 PUSH(XSLT_OP_ATTR, NULL, URL);
1205                 return;
1206             }
1207             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1208             xsltGenericError(xsltGenericErrorContext,
1209                     "xsltCompileStepPattern : Name expected\n");
1210             ctxt->error = 1;
1211             goto error;
1212         }
1213         PUSH(XSLT_OP_ATTR, token, URL);
1214         return;
1215     }
1216     if (token == NULL)
1217         token = xsltScanName(ctxt);
1218     if (token == NULL) {
1219         if (CUR == '*') {
1220             NEXT;
1221             PUSH(XSLT_OP_ALL, token, NULL);
1222             goto parse_predicate;
1223         } else {
1224             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1225             xsltGenericError(xsltGenericErrorContext,
1226                     "xsltCompileStepPattern : Name expected\n");
1227             ctxt->error = 1;
1228             goto error;
1229         }
1230     }
1231
1232
1233     SKIP_BLANKS;
1234     if (CUR == '(') {
1235         xsltCompileIdKeyPattern(ctxt, token, 0);
1236         if (ctxt->error)
1237             goto error;
1238     } else if (CUR == ':') {
1239         NEXT;
1240         if (CUR != ':') {
1241             xmlChar *prefix = token;
1242             xmlNsPtr ns;
1243
1244             /*
1245              * This is a namespace match
1246              */
1247             token = xsltScanName(ctxt);
1248             ns = xmlSearchNs(ctxt->doc, ctxt->elem, prefix);
1249             if (ns == NULL) {
1250                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1251                 xsltGenericError(xsltGenericErrorContext,
1252             "xsltCompileStepPattern : no namespace bound to prefix %s\n",
1253                                  prefix);
1254                 ctxt->error = 1;
1255                 goto error;
1256             } else {
1257                 URL = xmlStrdup(ns->href);
1258             }
1259             xmlFree(prefix);
1260             if (token == NULL) {
1261                 if (CUR == '*') {
1262                     NEXT;
1263                     PUSH(XSLT_OP_NS, URL, NULL);
1264                 } else {
1265                     xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1266                     xsltGenericError(xsltGenericErrorContext,
1267                             "xsltCompileStepPattern : Name expected\n");
1268                     ctxt->error = 1;
1269                     goto error;
1270                 }
1271             } else {
1272                 PUSH(XSLT_OP_ELEM, token, URL);
1273             }
1274         } else {
1275             NEXT;
1276             if (xmlStrEqual(token, (const xmlChar *) "child")) {
1277                 xmlFree(token);
1278                 token = xsltScanName(ctxt);
1279                 if (token == NULL) {
1280                     xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1281                     xsltGenericError(xsltGenericErrorContext,
1282                             "xsltCompileStepPattern : QName expected\n");
1283                     ctxt->error = 1;
1284                     goto error;
1285                 }
1286                 URI = xsltGetQNameURI(ctxt->elem, &token);
1287                 if (token == NULL) {
1288                     ctxt->error = 1;
1289                     goto error;
1290                 } else {
1291                     name = xmlStrdup(token);
1292                     if (URI != NULL)
1293                         URL = xmlStrdup(URI);
1294                 }
1295                 PUSH(XSLT_OP_CHILD, name, URL);
1296             } else if (xmlStrEqual(token, (const xmlChar *) "attribute")) {
1297                 xmlFree(token);
1298                 token = xsltScanName(ctxt);
1299                 if (token == NULL) {
1300                     xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1301                     xsltGenericError(xsltGenericErrorContext,
1302                             "xsltCompileStepPattern : QName expected\n");
1303                     ctxt->error = 1;
1304                     goto error;
1305                 }
1306                 URI = xsltGetQNameURI(ctxt->elem, &token);
1307                 if (token == NULL) {
1308                     ctxt->error = 1;
1309                     goto error;
1310                 } else {
1311                     name = xmlStrdup(token);
1312                     if (URI != NULL)
1313                         URL = xmlStrdup(URI);
1314                 }
1315                 PUSH(XSLT_OP_ATTR, name, URL);
1316             } else {
1317                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1318                 xsltGenericError(xsltGenericErrorContext,
1319                     "xsltCompileStepPattern : 'child' or 'attribute' expected\n");
1320                 ctxt->error = 1;
1321                 goto error;
1322             }
1323             xmlFree(token);
1324         }
1325     } else if (CUR == '*') {
1326         NEXT;
1327         PUSH(XSLT_OP_ALL, token, NULL);
1328     } else {
1329         URI = xsltGetQNameURI(ctxt->elem, &token);
1330         if (token == NULL) {
1331             ctxt->error = 1;
1332             goto error;
1333         }
1334         if (URI != NULL)
1335             URL = xmlStrdup(URI);
1336         PUSH(XSLT_OP_ELEM, token, URL);
1337     }
1338 parse_predicate:
1339     SKIP_BLANKS;
1340     level = 0;
1341     while (CUR == '[') {
1342         const xmlChar *q;
1343         xmlChar *ret = NULL;
1344
1345         level++;
1346         NEXT;
1347         q = CUR_PTR;
1348         /* TODO: avoid breaking in strings ... */
1349         while (IS_CHAR(CUR)) {
1350             /* Skip over nested predicates */
1351             if (CUR == '[')
1352                 level++;
1353             if (CUR == ']') {
1354                 level--;
1355                 if (level == 0)
1356                     break;
1357             }
1358             NEXT;
1359         }
1360         if (!IS_CHAR(CUR)) {
1361             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1362             xsltGenericError(xsltGenericErrorContext,
1363                     "xsltCompileStepPattern : ']' expected\n");
1364             ctxt->error = 1;
1365             goto error;
1366         }
1367         ret = xmlStrndup(q, CUR_PTR - q);
1368         PUSH(XSLT_OP_PREDICATE, ret, NULL);
1369         /* push the predicate lower than local test */
1370         SWAP();
1371         NEXT;
1372     }
1373     return;
1374 error:
1375     if (token != NULL)
1376         xmlFree(token);
1377     if (name != NULL)
1378         xmlFree(name);
1379 }
1380
1381 /**
1382  * xsltCompileRelativePathPattern:
1383  * @comp:  the compilation context
1384  * @token:  a posible precompiled name
1385  *
1386  * Compile the XSLT RelativePathPattern and generates a precompiled
1387  * form suitable for fast matching.
1388  *
1389  * [4] RelativePathPattern ::= StepPattern
1390  *                           | RelativePathPattern '/' StepPattern
1391  *                           | RelativePathPattern '//' StepPattern
1392  */
1393 static void
1394 xsltCompileRelativePathPattern(xsltParserContextPtr ctxt, xmlChar *token) {
1395     xsltCompileStepPattern(ctxt, token);
1396     if (ctxt->error)
1397         goto error;
1398     SKIP_BLANKS;
1399     while ((CUR != 0) && (CUR != '|')) {
1400         if ((CUR == '/') && (NXT(1) == '/')) {
1401             PUSH(XSLT_OP_ANCESTOR, NULL, NULL);
1402             NEXT;
1403             NEXT;
1404             SKIP_BLANKS;
1405             xsltCompileStepPattern(ctxt, NULL);
1406         } else if (CUR == '/') {
1407             PUSH(XSLT_OP_PARENT, NULL, NULL);
1408             NEXT;
1409             SKIP_BLANKS;
1410             if ((CUR != 0) || (CUR == '|')) {
1411                 xsltCompileRelativePathPattern(ctxt, NULL);
1412             }
1413         } else {
1414             ctxt->error = 1;
1415         }
1416         if (ctxt->error)
1417             goto error;
1418         SKIP_BLANKS;
1419     }
1420 error:
1421     return;
1422 }
1423
1424 /**
1425  * xsltCompileLocationPathPattern:
1426  * @ctxt:  the compilation context
1427  *
1428  * Compile the XSLT LocationPathPattern and generates a precompiled
1429  * form suitable for fast matching.
1430  *
1431  * [2] LocationPathPattern ::= '/' RelativePathPattern?
1432  *                           | IdKeyPattern (('/' | '//') RelativePathPattern)?
1433  *                           | '//'? RelativePathPattern
1434  */
1435 static void
1436 xsltCompileLocationPathPattern(xsltParserContextPtr ctxt) {
1437     SKIP_BLANKS;
1438     if ((CUR == '/') && (NXT(1) == '/')) {
1439         /*
1440          * since we reverse the query
1441          * a leading // can be safely ignored
1442          */
1443         NEXT;
1444         NEXT;
1445         xsltCompileRelativePathPattern(ctxt, NULL);
1446     } else if (CUR == '/') {
1447         /*
1448          * We need to find root as the parent
1449          */
1450         NEXT;
1451         SKIP_BLANKS;
1452         PUSH(XSLT_OP_ROOT, NULL, NULL);
1453         if ((CUR != 0) || (CUR == '|')) {
1454             PUSH(XSLT_OP_PARENT, NULL, NULL);
1455             xsltCompileRelativePathPattern(ctxt, NULL);
1456         }
1457     } else if (CUR == '*') {
1458         xsltCompileRelativePathPattern(ctxt, NULL);
1459     } else if (CUR == '@') {
1460         xsltCompileRelativePathPattern(ctxt, NULL);
1461     } else {
1462         xmlChar *name;
1463         name = xsltScanName(ctxt);
1464         if (name == NULL) {
1465             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1466             xsltGenericError(xsltGenericErrorContext,
1467                     "xsltCompileLocationPathPattern : Name expected\n");
1468             ctxt->error = 1;
1469             return;
1470         }
1471         SKIP_BLANKS;
1472         if ((CUR == '(') && !xmlXPathIsNodeType(name)) {
1473             xsltCompileIdKeyPattern(ctxt, name, 1);
1474             if ((CUR == '/') && (NXT(1) == '/')) {
1475                 PUSH(XSLT_OP_ANCESTOR, NULL, NULL);
1476                 NEXT;
1477                 NEXT;
1478                 SKIP_BLANKS;
1479                 xsltCompileRelativePathPattern(ctxt, NULL);
1480             } else if (CUR == '/') {
1481                 PUSH(XSLT_OP_PARENT, NULL, NULL);
1482                 NEXT;
1483                 SKIP_BLANKS;
1484                 xsltCompileRelativePathPattern(ctxt, NULL);
1485             }
1486             return;
1487         }
1488         xsltCompileRelativePathPattern(ctxt, name);
1489     }
1490 error:
1491     return;
1492 }
1493
1494 /**
1495  * xsltCompilePattern:
1496  * @pattern: an XSLT pattern
1497  * @doc:  the containing document
1498  * @node:  the containing element
1499  *
1500  * Compile the XSLT pattern and generates a list of precompiled form suitable
1501  * for fast matching.
1502  *
1503  * [1] Pattern ::= LocationPathPattern | Pattern '|' LocationPathPattern
1504  *
1505  * Returns the generated pattern list or NULL in case of failure
1506  */
1507
1508 xsltCompMatchPtr
1509 xsltCompilePattern(const xmlChar *pattern, xmlDocPtr doc, xmlNodePtr node) {
1510     xsltParserContextPtr ctxt = NULL;
1511     xsltCompMatchPtr element, first = NULL, previous = NULL;
1512     int current, start, end;
1513
1514     if (pattern == NULL) {
1515         xsltPrintErrorContext(NULL, NULL, node); /* TODO */
1516         xsltGenericError(xsltGenericErrorContext,
1517                          "xsltCompilePattern : NULL pattern\n");
1518         return(NULL);
1519     }
1520
1521     ctxt = xsltNewParserContext();
1522     if (ctxt == NULL)
1523         return(NULL);
1524     ctxt->doc = doc;
1525     ctxt->elem = node;
1526     current = end = 0;
1527     while (pattern[current] != 0) {
1528         start = current;
1529         while (IS_BLANK(pattern[current]))
1530             current++;
1531         end = current;
1532         while ((pattern[end] != 0) && (pattern[end] != '|'))
1533             end++;
1534         if (current == end) {
1535             xsltPrintErrorContext(NULL, NULL, node); /* TODO */
1536             xsltGenericError(xsltGenericErrorContext,
1537                              "xsltCompilePattern : NULL pattern\n");
1538             goto error;
1539         }
1540         element = xsltNewCompMatch();
1541         if (element == NULL) {
1542             goto error;
1543         }
1544         if (first == NULL)
1545             first = element;
1546         else if (previous != NULL)
1547             previous->next = element;
1548         previous = element;
1549
1550         ctxt->comp = element;
1551         ctxt->base = xmlStrndup(&pattern[start], end - start);
1552         if (ctxt->base == NULL)
1553             goto error;
1554         ctxt->cur = &(ctxt->base)[current - start];
1555         element->pattern = ctxt->base;
1556
1557 #ifdef WITH_XSLT_DEBUG_PATTERN
1558         xsltGenericDebug(xsltGenericDebugContext,
1559                          "xsltCompilePattern : parsing '%s'\n",
1560                          element->pattern);
1561 #endif
1562         xsltCompileLocationPathPattern(ctxt);
1563         if (ctxt->error)
1564             goto error;
1565
1566         /*
1567          * Reverse for faster interpretation.
1568          */
1569         xsltReverseCompMatch(element);
1570
1571         /*
1572          * Set-up the priority
1573          */
1574         if (((element->steps[0].op == XSLT_OP_ELEM) ||
1575              (element->steps[0].op == XSLT_OP_ATTR)) &&
1576             (element->steps[0].value != NULL) &&
1577             (element->steps[1].op == XSLT_OP_END)) {
1578             element->priority = 0;
1579 #if 0
1580         } else if ((element->steps[0].op == XSLT_OP_ROOT) &&
1581                    (element->steps[1].op == XSLT_OP_END)) {
1582             element->priority = 0;
1583 #endif
1584         } else if ((element->steps[0].op == XSLT_OP_PI) &&
1585                    (element->steps[0].value != NULL) &&
1586                    (element->steps[1].op == XSLT_OP_END)) {
1587             element->priority = 0;
1588         } else if ((element->steps[0].op == XSLT_OP_ATTR) &&
1589                    (element->steps[0].value2 != NULL) &&
1590                    (element->steps[1].op == XSLT_OP_END)) {
1591             element->priority = -0.25;
1592         } else if ((element->steps[0].op == XSLT_OP_NS) &&
1593                    (element->steps[0].value != NULL) &&
1594                    (element->steps[1].op == XSLT_OP_END)) {
1595             element->priority = -0.25;
1596         } else if ((element->steps[0].op == XSLT_OP_ATTR) &&
1597                    (element->steps[0].value == NULL) &&
1598                    (element->steps[0].value2 == NULL) &&
1599                    (element->steps[1].op == XSLT_OP_END)) {
1600             element->priority = -0.5;
1601         } else if (((element->steps[0].op == XSLT_OP_PI) ||
1602                     (element->steps[0].op == XSLT_OP_TEXT) ||
1603                     (element->steps[0].op == XSLT_OP_ALL) ||
1604                     (element->steps[0].op == XSLT_OP_NODE) ||
1605                     (element->steps[0].op == XSLT_OP_COMMENT)) &&
1606                    (element->steps[1].op == XSLT_OP_END)) {
1607             element->priority = -0.5;
1608         } else {
1609             element->priority = 0.5;
1610         }
1611 #ifdef WITH_XSLT_DEBUG_PATTERN
1612         xsltGenericDebug(xsltGenericDebugContext,
1613                      "xsltCompilePattern : parsed %s, default priority %f\n",
1614                          element->pattern, element->priority);
1615 #endif
1616         if (pattern[end] == '|')
1617             end++;
1618         current = end;
1619     }
1620     if (end == 0) {
1621         xsltPrintErrorContext(NULL, NULL, node); /* TODO */
1622         xsltGenericError(xsltGenericErrorContext,
1623                          "xsltCompilePattern : NULL pattern\n");
1624         goto error;
1625     }
1626
1627     xsltFreeParserContext(ctxt);
1628     return(first);
1629
1630 error:
1631     if (ctxt != NULL)
1632         xsltFreeParserContext(ctxt);
1633     if (first != NULL)
1634         xsltFreeCompMatchList(first);
1635     return(NULL);
1636 }
1637
1638 /************************************************************************
1639  *                                                                      *
1640  *                      Module interfaces                               *
1641  *                                                                      *
1642  ************************************************************************/
1643
1644 /**
1645  * xsltAddTemplate:
1646  * @style: an XSLT stylesheet
1647  * @cur: an XSLT template
1648  * @mode:  the mode name or NULL
1649  * @modeURI:  the mode URI or NULL
1650  *
1651  * Register the XSLT pattern associated to @cur
1652  *
1653  * Returns -1 in case of error, 0 otherwise
1654  */
1655 int
1656 xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur,
1657                 const xmlChar *mode, const xmlChar *modeURI) {
1658     xsltCompMatchPtr pat, list, *top = NULL, next;
1659     const xmlChar *name = NULL;
1660     float priority;              /* the priority */
1661
1662     if ((style == NULL) || (cur == NULL) || (cur->match == NULL))
1663         return(-1);
1664
1665     priority = cur->priority;
1666     pat = xsltCompilePattern(cur->match, style->doc, cur->elem);
1667     while (pat) {
1668         next = pat->next;
1669         pat->next = NULL;
1670         name = NULL;
1671         
1672         pat->template = cur;
1673         if (mode != NULL)
1674             pat->mode = xmlStrdup(mode);
1675         if (modeURI != NULL)
1676             pat->modeURI = xmlStrdup(modeURI);
1677         if (priority != XSLT_PAT_NO_PRIORITY)
1678             pat->priority = priority;
1679
1680         /*
1681          * insert it in the hash table list corresponding to its lookup name
1682          */
1683         switch (pat->steps[0].op) {
1684         case XSLT_OP_ATTR:
1685             if (pat->steps[0].value != NULL)
1686                 name = pat->steps[0].value;
1687             else
1688                 top = (xsltCompMatchPtr *) &(style->attrMatch);
1689             break;
1690         case XSLT_OP_ELEM:
1691         case XSLT_OP_CHILD:
1692         case XSLT_OP_PARENT:
1693         case XSLT_OP_ANCESTOR:
1694             top = (xsltCompMatchPtr *) &(style->elemMatch);
1695             break;
1696         case XSLT_OP_ROOT:
1697             top = (xsltCompMatchPtr *) &(style->rootMatch);
1698             break;
1699         case XSLT_OP_KEY:
1700             top = (xsltCompMatchPtr *) &(style->keyMatch);
1701             break;
1702         case XSLT_OP_ID:
1703             /* TODO optimize ID !!! */
1704         case XSLT_OP_NS:
1705         case XSLT_OP_ALL:
1706             top = (xsltCompMatchPtr *) &(style->elemMatch);
1707             break;
1708         case XSLT_OP_END:
1709         case XSLT_OP_PREDICATE:
1710             xsltPrintErrorContext(NULL, style, NULL);
1711             xsltGenericError(xsltGenericErrorContext,
1712                              "xsltAddTemplate: invalid compiled pattern\n");
1713             xsltFreeCompMatch(pat);
1714             return(-1);
1715             /*
1716              * TODO: some flags at the top level about type based patterns
1717              *       would be faster than inclusion in the hash table.
1718              */
1719         case XSLT_OP_PI:
1720             if (pat->steps[0].value != NULL)
1721                 name = pat->steps[0].value;
1722             else
1723                 top = (xsltCompMatchPtr *) &(style->piMatch);
1724             break;
1725         case XSLT_OP_COMMENT:
1726             top = (xsltCompMatchPtr *) &(style->commentMatch);
1727             break;
1728         case XSLT_OP_TEXT:
1729             top = (xsltCompMatchPtr *) &(style->textMatch);
1730             break;
1731         case XSLT_OP_NODE:
1732             if (pat->steps[0].value != NULL)
1733                 name = pat->steps[0].value;
1734             else
1735                 top = (xsltCompMatchPtr *) &(style->elemMatch);
1736             
1737             break;
1738         }
1739         if (name != NULL) {
1740             if (style->templatesHash == NULL) {
1741                 style->templatesHash = xmlHashCreate(1024);
1742                 if (style->templatesHash == NULL) {
1743                     xsltFreeCompMatch(pat);
1744                     return(-1);
1745                 }
1746                 xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat);
1747             } else {
1748                 list = (xsltCompMatchPtr) xmlHashLookup3(style->templatesHash,
1749                                                          name, mode, modeURI);
1750                 if (list == NULL) {
1751                     xmlHashAddEntry3(style->templatesHash, name,
1752                                      mode, modeURI, pat);
1753                 } else {
1754                     /*
1755                      * Note '<=' since one must choose among the matching
1756                      * template rules that are left, the one that occurs
1757                      * last in the stylesheet
1758                      */
1759                     if (list->priority <= pat->priority) {
1760                         pat->next = list;
1761                         xmlHashUpdateEntry3(style->templatesHash, name,
1762                                             mode, modeURI, pat, NULL);
1763                     } else {
1764                         while (list->next != NULL) {
1765                             if (list->next->priority <= pat->priority)
1766                                 break;
1767                             list = list->next;
1768                         }
1769                         pat->next = list->next;
1770                         list->next = pat;
1771                     }
1772                 }
1773             }
1774         } else if (top != NULL) {
1775             list = *top;
1776             if (list == NULL) {
1777                 *top = pat;
1778                 pat->next = NULL;
1779             } else if (list->priority <= pat->priority) {
1780                 pat->next = list;
1781                 *top = pat;
1782             } else {
1783                 while (list->next != NULL) {
1784                     if (list->next->priority <= pat->priority)
1785                         break;
1786                     list = list->next;
1787                 }
1788                 pat->next = list->next;
1789                 list->next = pat;
1790             }
1791         } else {
1792             xsltPrintErrorContext(NULL, style, NULL);
1793             xsltGenericError(xsltGenericErrorContext,
1794                              "xsltAddTemplate: invalid compiled pattern\n");
1795             xsltFreeCompMatch(pat);
1796             return(-1);
1797         }
1798 #ifdef WITH_XSLT_DEBUG_PATTERN
1799         if (mode)
1800             xsltGenericDebug(xsltGenericDebugContext,
1801                          "added pattern : '%s' mode '%s' priority %f\n",
1802                              pat->pattern, pat->mode, pat->priority);
1803         else
1804             xsltGenericDebug(xsltGenericDebugContext,
1805                          "added pattern : '%s' priority %f\n",
1806                              pat->pattern, pat->priority);
1807 #endif
1808
1809         pat = next;
1810     }
1811     return(0);
1812 }
1813
1814 /**
1815  * xsltGetTemplate:
1816  * @ctxt:  a XSLT process context
1817  * @node:  the node being processed
1818  * @style:  the current style
1819  *
1820  * Finds the template applying to this node, if @style is non-NULL
1821  * it means one needs to look for the next imported template in scope.
1822  *
1823  * Returns the xsltTemplatePtr or NULL if not found
1824  */
1825 xsltTemplatePtr
1826 xsltGetTemplate(xsltTransformContextPtr ctxt, xmlNodePtr node,
1827                 xsltStylesheetPtr style) {
1828     xsltStylesheetPtr curstyle;
1829     xsltTemplatePtr ret = NULL;
1830     const xmlChar *name = NULL;
1831     xsltCompMatchPtr list = NULL;
1832     float priority;
1833
1834     if ((ctxt == NULL) || (node == NULL))
1835         return(NULL);
1836
1837     if (style == NULL) {
1838         curstyle = ctxt->style;
1839     } else {
1840         curstyle = xsltNextImport(style);
1841     }
1842
1843     while ((curstyle != NULL) && (curstyle != style)) {
1844         priority = XSLT_PAT_NO_PRIORITY;
1845         /* TODO : handle IDs/keys here ! */
1846         if (curstyle->templatesHash != NULL) {
1847             /*
1848              * Use the top name as selector
1849              */
1850             switch (node->type) {
1851                 case XML_ELEMENT_NODE:
1852                 case XML_ATTRIBUTE_NODE:
1853                 case XML_PI_NODE:
1854                     name = node->name;
1855                     break;
1856                 case XML_DOCUMENT_NODE:
1857                 case XML_HTML_DOCUMENT_NODE:
1858                 case XML_TEXT_NODE:
1859                 case XML_CDATA_SECTION_NODE:
1860                 case XML_COMMENT_NODE:
1861                 case XML_ENTITY_REF_NODE:
1862                 case XML_ENTITY_NODE:
1863                 case XML_DOCUMENT_TYPE_NODE:
1864                 case XML_DOCUMENT_FRAG_NODE:
1865                 case XML_NOTATION_NODE:
1866                 case XML_DTD_NODE:
1867                 case XML_ELEMENT_DECL:
1868                 case XML_ATTRIBUTE_DECL:
1869                 case XML_ENTITY_DECL:
1870                 case XML_NAMESPACE_DECL:
1871                 case XML_XINCLUDE_START:
1872                 case XML_XINCLUDE_END:
1873                     break;
1874                 default:
1875                     return(NULL);
1876
1877             }
1878         }
1879         if (name != NULL) {
1880             /*
1881              * find the list of appliable expressions based on the name
1882              */
1883             list = (xsltCompMatchPtr) xmlHashLookup3(curstyle->templatesHash,
1884                                              name, ctxt->mode, ctxt->modeURI);
1885         } else
1886             list = NULL;
1887         while (list != NULL) {
1888             if (xsltTestCompMatch(ctxt, list, node,
1889                                   ctxt->mode, ctxt->modeURI)) {
1890                 ret = list->template;
1891                 priority = list->priority;
1892                 break;
1893             }
1894             list = list->next;
1895         }
1896         list = NULL;
1897
1898         /*
1899          * find alternate generic matches
1900          */
1901         switch (node->type) {
1902             case XML_ELEMENT_NODE:
1903                 list = curstyle->elemMatch;
1904                 break;
1905             case XML_ATTRIBUTE_NODE:
1906                 list = curstyle->attrMatch;
1907                 break;
1908             case XML_PI_NODE:
1909                 list = curstyle->piMatch;
1910                 break;
1911             case XML_DOCUMENT_NODE:
1912             case XML_HTML_DOCUMENT_NODE:
1913                 list = curstyle->rootMatch;
1914                 break;
1915             case XML_TEXT_NODE:
1916             case XML_CDATA_SECTION_NODE:
1917                 list = curstyle->textMatch;
1918                 break;
1919             case XML_COMMENT_NODE:
1920                 list = curstyle->commentMatch;
1921                 break;
1922             case XML_ENTITY_REF_NODE:
1923             case XML_ENTITY_NODE:
1924             case XML_DOCUMENT_TYPE_NODE:
1925             case XML_DOCUMENT_FRAG_NODE:
1926             case XML_NOTATION_NODE:
1927             case XML_DTD_NODE:
1928             case XML_ELEMENT_DECL:
1929             case XML_ATTRIBUTE_DECL:
1930             case XML_ENTITY_DECL:
1931             case XML_NAMESPACE_DECL:
1932             case XML_XINCLUDE_START:
1933             case XML_XINCLUDE_END:
1934                 break;
1935             default:
1936                 break;
1937
1938         }
1939         while ((list != NULL) &&
1940                ((ret == NULL)  || (list->priority > priority))) {
1941             if (xsltTestCompMatch(ctxt, list, node,
1942                                   ctxt->mode, ctxt->modeURI)) {
1943                 ret = list->template;
1944                 break;
1945             }
1946             list = list->next;
1947         }
1948         /*
1949          * Some of the tests for elements can also apply to documents
1950          */
1951         if ((node->type == XML_DOCUMENT_NODE) ||
1952             (node->type == XML_HTML_DOCUMENT_NODE)) {
1953             list = curstyle->elemMatch;
1954             while ((list != NULL) &&
1955                    ((ret == NULL)  || (list->priority > priority))) {
1956                 if (xsltTestCompMatch(ctxt, list, node,
1957                                       ctxt->mode, ctxt->modeURI)) {
1958                     ret = list->template;
1959                     break;
1960                 }
1961                 list = list->next;
1962             }
1963         }
1964
1965         if (node->_private != NULL) {
1966             list = curstyle->keyMatch;
1967             while ((list != NULL) &&
1968                    ((ret == NULL)  || (list->priority > priority))) {
1969                 if (xsltTestCompMatch(ctxt, list, node,
1970                                       ctxt->mode, ctxt->modeURI)) {
1971                     ret = list->template;
1972                     break;
1973                 }
1974                 list = list->next;
1975             }
1976         }
1977         if (ret != NULL)
1978             return(ret);
1979
1980         /*
1981          * Cycle on next curstylesheet import.
1982          */
1983         curstyle = xsltNextImport(curstyle);
1984     }
1985     return(NULL);
1986 }
1987
1988 /**
1989  * xsltCleanupTemplates:
1990  * @style: an XSLT stylesheet
1991  *
1992  * Cleanup the state of the templates used by the stylesheet and
1993  * the ones it imports.
1994  */
1995 void
1996 xsltCleanupTemplates(xsltStylesheetPtr style) {
1997     while (style != NULL) {
1998         xmlHashScan((xmlHashTablePtr) style->templatesHash,
1999                     (xmlHashScanner) xsltCleanupCompMatch, NULL);
2000
2001         style = xsltNextImport(style);
2002     }
2003 }
2004
2005 /**
2006  * xsltFreeTemplateHashes:
2007  * @style: an XSLT stylesheet
2008  *
2009  * Free up the memory used by xsltAddTemplate/xsltGetTemplate mechanism
2010  */
2011 void
2012 xsltFreeTemplateHashes(xsltStylesheetPtr style) {
2013     if (style->templatesHash != NULL)
2014         xmlHashFree((xmlHashTablePtr) style->templatesHash,
2015                     (xmlHashDeallocator) xsltFreeCompMatchList);
2016     if (style->rootMatch != NULL)
2017         xsltFreeCompMatchList(style->rootMatch);
2018     if (style->keyMatch != NULL)
2019         xsltFreeCompMatchList(style->keyMatch);
2020     if (style->elemMatch != NULL)
2021         xsltFreeCompMatchList(style->elemMatch);
2022     if (style->attrMatch != NULL)
2023         xsltFreeCompMatchList(style->attrMatch);
2024     if (style->parentMatch != NULL)
2025         xsltFreeCompMatchList(style->parentMatch);
2026     if (style->textMatch != NULL)
2027         xsltFreeCompMatchList(style->textMatch);
2028     if (style->piMatch != NULL)
2029         xsltFreeCompMatchList(style->piMatch);
2030     if (style->commentMatch != NULL)
2031         xsltFreeCompMatchList(style->commentMatch);
2032 }
2033
2034 #if 0
2035 /**
2036  * xsltMatchPattern
2037  * @node: a node in the source tree
2038  * @pattern: an XSLT pattern
2039  *
2040  * Determine if a node matches a pattern.
2041  */
2042 int
2043 xsltMatchPattern(xsltTransformContextPtr context,
2044                  xmlNodePtr node,
2045                  const xmlChar *pattern)
2046 {
2047     int match = 0;
2048     xsltCompMatchPtr first, comp;
2049
2050     if ((context != NULL) && (pattern != NULL)) {
2051         first = xsltCompilePattern(pattern);
2052         for (comp = first; comp != NULL; comp = comp->next) {
2053             match = xsltTestCompMatch(context, comp, node, NULL, NULL);
2054             if (match)
2055                 break; /* for */
2056         }
2057         if (first)
2058             xsltFreeCompMatchList(first);
2059     }
2060     return match;
2061 }
2062 #endif