fixed I18N problemes in the template parser pointed out by Xavier Cazin
[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[40];        /* 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 = 40;
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 >= 40) {
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 #ifdef LIBXML_DOCB_ENABLED
763                     case XML_DOCB_DOCUMENT_NODE:
764 #endif
765                     case XML_ELEMENT_NODE:
766                     case XML_CDATA_SECTION_NODE:
767                     case XML_PI_NODE:
768                     case XML_COMMENT_NODE:
769                     case XML_TEXT_NODE:
770                     case XML_ATTRIBUTE_NODE:
771                         break;
772                     default:
773                         return(0);
774                 }
775                 break;
776         }
777     }
778     return(1);
779 }
780
781 /**
782  * xsltTestCompMatchList:
783  * @ctxt:  a XSLT process context
784  * @node: a node
785  * @comp: the precompiled pattern list
786  *
787  * Test wether the node matches one of the patterns in the list
788  *
789  * Returns 1 if it matches, 0 if it doesn't and -1 in case of failure
790  */
791 int
792 xsltTestCompMatchList(xsltTransformContextPtr ctxt, xmlNodePtr node,
793                       xsltCompMatchPtr comp) {
794     int ret;
795
796     if ((ctxt == NULL) || (node == NULL))
797         return(-1);
798     while (comp != NULL) {
799         ret = xsltTestCompMatch(ctxt, comp, node, NULL, NULL);
800         if (ret == 1)
801             return(1);
802         comp = comp->next;
803     }
804     return(0);
805 }
806
807 /************************************************************************
808  *                                                                      *
809  *                      Dedicated parser for templates                  *
810  *                                                                      *
811  ************************************************************************/
812
813 #define CUR (*ctxt->cur)
814 #define SKIP(val) ctxt->cur += (val)
815 #define NXT(val) ctxt->cur[(val)]
816 #define CUR_PTR ctxt->cur
817
818 #define SKIP_BLANKS                                                     \
819     while (IS_BLANK(CUR)) NEXT
820
821 #define CURRENT (*ctxt->cur)
822 #define NEXT ((*ctxt->cur) ?  ctxt->cur++: ctxt->cur)
823
824
825 #define PUSH(op, val, val2)                                             \
826     if (xsltCompMatchAdd(ctxt->comp, (op), (val), (val2))) goto error;
827
828 #define SWAP()                                          \
829     xsltSwapTopCompMatch(ctxt->comp);
830
831 #define XSLT_ERROR(X)                                                   \
832     { xsltError(ctxt, __FILE__, __LINE__, X);                   \
833       ctxt->error = (X); return; }
834
835 #define XSLT_ERROR0(X)                                                  \
836     { xsltError(ctxt, __FILE__, __LINE__, X);                   \
837       ctxt->error = (X); return(0); }
838
839 /**
840  * xsltScanLiteral:
841  * @ctxt:  the XPath Parser context
842  *
843  * Parse an XPath Litteral:
844  *
845  * [29] Literal ::= '"' [^"]* '"'
846  *                | "'" [^']* "'"
847  *
848  * Returns the Literal parsed or NULL
849  */
850
851 static xmlChar *
852 xsltScanLiteral(xsltParserContextPtr ctxt) {
853     const xmlChar *q, *cur;
854     xmlChar *ret = NULL;
855     int val, len;
856
857     SKIP_BLANKS;
858     if (CUR == '"') {
859         NEXT;
860         cur = q = CUR_PTR;
861         val = xmlStringCurrentChar(NULL, cur, &len);
862         while ((IS_CHAR(val)) && (val != '"')) {
863             cur += len;
864             val = xmlStringCurrentChar(NULL, cur, &len);
865         }
866         if (!IS_CHAR(val)) {
867             ctxt->error = 1;
868             return(NULL);
869         } else {
870             ret = xmlStrndup(q, cur - q);
871         }
872         cur += len;
873         CUR_PTR = cur;
874     } else if (CUR == '\'') {
875         NEXT;
876         cur = q = CUR_PTR;
877         val = xmlStringCurrentChar(NULL, cur, &len);
878         while ((IS_CHAR(val)) && (val != '\'')) {
879             cur += len;
880             val = xmlStringCurrentChar(NULL, cur, &len);
881         }
882         if (!IS_CHAR(val)) {
883             ctxt->error = 1;
884             return(NULL);
885         } else {
886             ret = xmlStrndup(q, cur - q);
887         }
888         cur += len;
889         CUR_PTR = cur;
890     } else {
891         /* XP_ERROR(XPATH_START_LITERAL_ERROR); */
892         ctxt->error = 1;
893         return(NULL);
894     }
895     return(ret);
896 }
897
898 /**
899  * xsltScanName:
900  * @ctxt:  the XPath Parser context
901  *
902  * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | 
903  *                  CombiningChar | Extender
904  *
905  * [5] Name ::= (Letter | '_' | ':') (NameChar)*
906  *
907  * [6] Names ::= Name (S Name)*
908  *
909  * Returns the Name parsed or NULL
910  */
911
912 static xmlChar *
913 xsltScanName(xsltParserContextPtr ctxt) {
914     const xmlChar *q, *cur;
915     xmlChar *ret = NULL;
916     int val, len;
917
918     SKIP_BLANKS;
919
920     cur = q = CUR_PTR;
921     val = xmlStringCurrentChar(NULL, cur, &len);
922     if (!IS_LETTER(val) && (val != '_') && (val != ':'))
923         return(NULL);
924
925     while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
926            (val == '.') || (val == '-') ||
927            (val == '_') || 
928            (IS_COMBINING(val)) ||
929            (IS_EXTENDER(val))) {
930         cur += len;
931         val = xmlStringCurrentChar(NULL, cur, &len);
932     }
933     ret = xmlStrndup(q, cur - q);
934     CUR_PTR = cur;
935     return(ret);
936 }
937
938 /**
939  * xsltScanNCName:
940  * @ctxt:  the XPath Parser context
941  *
942  * Parses a non qualified name
943  *
944  * Returns the Name parsed or NULL
945  */
946
947 static xmlChar *
948 xsltScanNCName(xsltParserContextPtr ctxt) {
949     const xmlChar *q, *cur;
950     xmlChar *ret = NULL;
951     int val, len;
952
953     SKIP_BLANKS;
954
955     cur = q = CUR_PTR;
956     val = xmlStringCurrentChar(NULL, cur, &len);
957     if (!IS_LETTER(val) && (val != '_'))
958         return(NULL);
959
960     while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
961            (val == '.') || (val == '-') ||
962            (val == '_') ||
963            (IS_COMBINING(val)) ||
964            (IS_EXTENDER(val))) {
965         cur += len;
966         val = xmlStringCurrentChar(NULL, cur, &len);
967     }
968     ret = xmlStrndup(q, cur - q);
969     CUR_PTR = cur;
970     return(ret);
971 }
972
973 /**
974  * xsltScanQName:
975  * @ctxt:  the XPath Parser context
976  * @prefix:  the place to store the prefix
977  *
978  * Parse a qualified name
979  *
980  * Returns the Name parsed or NULL
981  */
982
983 static xmlChar *
984 xsltScanQName(xsltParserContextPtr ctxt, xmlChar **prefix) {
985     xmlChar *ret = NULL;
986
987     *prefix = NULL;
988     ret = xsltScanNCName(ctxt);
989     if (CUR == ':') {
990         *prefix = ret;
991         NEXT;
992         ret = xsltScanNCName(ctxt);
993     }
994     return(ret);
995 }
996
997 /*
998  * xsltCompileIdKeyPattern:
999  * @ctxt:  the compilation context
1000  * @name:  a preparsed name
1001  * @aid:  whether id/key are allowed there
1002  *
1003  * Compile the XSLT LocationIdKeyPattern
1004  * [3] IdKeyPattern ::= 'id' '(' Literal ')'
1005  *                    | 'key' '(' Literal ',' Literal ')'
1006  *
1007  * also handle NodeType and PI from:
1008  *
1009  * [7]  NodeTest ::= NameTest
1010  *                 | NodeType '(' ')'
1011  *                 | 'processing-instruction' '(' Literal ')'
1012  */
1013 static void
1014 xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name, int aid) {
1015     xmlChar *lit = NULL;
1016     xmlChar *lit2 = NULL;
1017
1018     if (CUR != '(') {
1019         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1020         xsltGenericError(xsltGenericErrorContext,
1021                 "xsltCompileIdKeyPattern : ( expected\n");
1022         ctxt->error = 1;
1023         return;
1024     }
1025     if ((aid) && (xmlStrEqual(name, (const xmlChar *)"id"))) {
1026         NEXT;
1027         SKIP_BLANKS;
1028         lit = xsltScanLiteral(ctxt);
1029         if (ctxt->error)
1030             return;
1031         SKIP_BLANKS;
1032         if (CUR != ')') {
1033             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1034             xsltGenericError(xsltGenericErrorContext,
1035                     "xsltCompileIdKeyPattern : ) expected\n");
1036             ctxt->error = 1;
1037             return;
1038         }
1039         NEXT;
1040         PUSH(XSLT_OP_ID, lit, NULL);
1041     } else if ((aid) && (xmlStrEqual(name, (const xmlChar *)"key"))) {
1042         NEXT;
1043         SKIP_BLANKS;
1044         lit = xsltScanLiteral(ctxt);
1045         if (ctxt->error)
1046             return;
1047         SKIP_BLANKS;
1048         if (CUR != ',') {
1049             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1050             xsltGenericError(xsltGenericErrorContext,
1051                     "xsltCompileIdKeyPattern : , expected\n");
1052             ctxt->error = 1;
1053             return;
1054         }
1055         NEXT;
1056         SKIP_BLANKS;
1057         lit2 = xsltScanLiteral(ctxt);
1058         if (ctxt->error)
1059             return;
1060         SKIP_BLANKS;
1061         if (CUR != ')') {
1062             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1063             xsltGenericError(xsltGenericErrorContext,
1064                     "xsltCompileIdKeyPattern : ) expected\n");
1065             ctxt->error = 1;
1066             return;
1067         }
1068         NEXT;
1069         /* TODO: support namespace in keys */
1070         PUSH(XSLT_OP_KEY, lit, lit2);
1071     } else if (xmlStrEqual(name, (const xmlChar *)"processing-instruction")) {
1072         NEXT;
1073         SKIP_BLANKS;
1074         if (CUR != ')') {
1075             lit = xsltScanLiteral(ctxt);
1076             if (ctxt->error)
1077                 return;
1078             SKIP_BLANKS;
1079             if (CUR != ')') {
1080                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1081                 xsltGenericError(xsltGenericErrorContext,
1082                         "xsltCompileIdKeyPattern : ) expected\n");
1083                 ctxt->error = 1;
1084                 return;
1085             }
1086         }
1087         NEXT;
1088         PUSH(XSLT_OP_PI, lit, NULL);
1089     } else if (xmlStrEqual(name, (const xmlChar *)"text")) {
1090         NEXT;
1091         SKIP_BLANKS;
1092         if (CUR != ')') {
1093             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1094             xsltGenericError(xsltGenericErrorContext,
1095                     "xsltCompileIdKeyPattern : ) expected\n");
1096             ctxt->error = 1;
1097             return;
1098         }
1099         NEXT;
1100         PUSH(XSLT_OP_TEXT, NULL, NULL);
1101     } else if (xmlStrEqual(name, (const xmlChar *)"comment")) {
1102         NEXT;
1103         SKIP_BLANKS;
1104         if (CUR != ')') {
1105             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1106             xsltGenericError(xsltGenericErrorContext,
1107                     "xsltCompileIdKeyPattern : ) expected\n");
1108             ctxt->error = 1;
1109             return;
1110         }
1111         NEXT;
1112         PUSH(XSLT_OP_COMMENT, NULL, NULL);
1113     } else if (xmlStrEqual(name, (const xmlChar *)"node")) {
1114         NEXT;
1115         SKIP_BLANKS;
1116         if (CUR != ')') {
1117             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1118             xsltGenericError(xsltGenericErrorContext,
1119                     "xsltCompileIdKeyPattern : ) expected\n");
1120             ctxt->error = 1;
1121             return;
1122         }
1123         NEXT;
1124         PUSH(XSLT_OP_NODE, NULL, NULL);
1125     } else if (aid) {
1126         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1127         xsltGenericError(xsltGenericErrorContext,
1128             "xsltCompileIdKeyPattern : expecting 'key' or 'id' or node type\n");
1129         ctxt->error = 1;
1130         return;
1131     } else {
1132         xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1133         xsltGenericError(xsltGenericErrorContext,
1134             "xsltCompileIdKeyPattern : node type\n");
1135         ctxt->error = 1;
1136         return;
1137     }
1138 error:
1139     if (name != NULL)
1140         xmlFree(name);
1141 }
1142
1143 /**
1144  * xsltCompileStepPattern:
1145  * @ctxt:  the compilation context
1146  * @token:  a posible precompiled name
1147  *
1148  * Compile the XSLT StepPattern and generates a precompiled
1149  * form suitable for fast matching.
1150  *
1151  * [5] StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate* 
1152  * [6] ChildOrAttributeAxisSpecifier ::= AbbreviatedAxisSpecifier
1153  *                                     | ('child' | 'attribute') '::'
1154  * from XPath
1155  * [7]  NodeTest ::= NameTest
1156  *                 | NodeType '(' ')'
1157  *                 | 'processing-instruction' '(' Literal ')'
1158  * [8] Predicate ::= '[' PredicateExpr ']'
1159  * [9] PredicateExpr ::= Expr
1160  * [13] AbbreviatedAxisSpecifier ::= '@'?
1161  * [37] NameTest ::= '*' | NCName ':' '*' | QName
1162  */
1163
1164 static void
1165 xsltCompileStepPattern(xsltParserContextPtr ctxt, xmlChar *token) {
1166     xmlChar *name = NULL;
1167     const xmlChar *URI = NULL;
1168     xmlChar *URL = NULL;
1169     int level;
1170
1171     SKIP_BLANKS;
1172     if ((token == NULL) && (CUR == '@')) {
1173         xmlChar *prefix = NULL;
1174
1175         NEXT;
1176         if (CUR == '*') {
1177             NEXT;
1178             PUSH(XSLT_OP_ATTR, NULL, NULL);
1179             return;
1180         }
1181         token = xsltScanQName(ctxt, &prefix);
1182         if (prefix != NULL) {
1183             xmlNsPtr ns;
1184
1185             ns = xmlSearchNs(ctxt->doc, ctxt->elem, prefix);
1186             if (ns == NULL) {
1187                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1188                 xsltGenericError(xsltGenericErrorContext,
1189                 "xsltCompileStepPattern : no namespace bound to prefix %s\n",
1190                                  prefix);
1191             } else {
1192                 URL = xmlStrdup(ns->href);
1193             }
1194             xmlFree(prefix);
1195         }
1196         if (token == NULL) {
1197             if (CUR == '*') {
1198                 NEXT;
1199                 PUSH(XSLT_OP_ATTR, NULL, URL);
1200                 return;
1201             }
1202             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1203             xsltGenericError(xsltGenericErrorContext,
1204                     "xsltCompileStepPattern : Name expected\n");
1205             ctxt->error = 1;
1206             goto error;
1207         }
1208         PUSH(XSLT_OP_ATTR, token, URL);
1209         return;
1210     }
1211     if (token == NULL)
1212         token = xsltScanName(ctxt);
1213     if (token == NULL) {
1214         if (CUR == '*') {
1215             NEXT;
1216             PUSH(XSLT_OP_ALL, token, NULL);
1217             goto parse_predicate;
1218         } else {
1219             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1220             xsltGenericError(xsltGenericErrorContext,
1221                     "xsltCompileStepPattern : Name expected\n");
1222             ctxt->error = 1;
1223             goto error;
1224         }
1225     }
1226
1227
1228     SKIP_BLANKS;
1229     if (CUR == '(') {
1230         xsltCompileIdKeyPattern(ctxt, token, 0);
1231         if (ctxt->error)
1232             goto error;
1233     } else if (CUR == ':') {
1234         NEXT;
1235         if (CUR != ':') {
1236             xmlChar *prefix = token;
1237             xmlNsPtr ns;
1238
1239             /*
1240              * This is a namespace match
1241              */
1242             token = xsltScanName(ctxt);
1243             ns = xmlSearchNs(ctxt->doc, ctxt->elem, prefix);
1244             if (ns == NULL) {
1245                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1246                 xsltGenericError(xsltGenericErrorContext,
1247             "xsltCompileStepPattern : no namespace bound to prefix %s\n",
1248                                  prefix);
1249                 ctxt->error = 1;
1250                 goto error;
1251             } else {
1252                 URL = xmlStrdup(ns->href);
1253             }
1254             xmlFree(prefix);
1255             if (token == NULL) {
1256                 if (CUR == '*') {
1257                     NEXT;
1258                     PUSH(XSLT_OP_NS, URL, NULL);
1259                 } else {
1260                     xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1261                     xsltGenericError(xsltGenericErrorContext,
1262                             "xsltCompileStepPattern : Name expected\n");
1263                     ctxt->error = 1;
1264                     goto error;
1265                 }
1266             } else {
1267                 PUSH(XSLT_OP_ELEM, token, URL);
1268             }
1269         } else {
1270             NEXT;
1271             if (xmlStrEqual(token, (const xmlChar *) "child")) {
1272                 xmlFree(token);
1273                 token = xsltScanName(ctxt);
1274                 if (token == NULL) {
1275                     xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1276                     xsltGenericError(xsltGenericErrorContext,
1277                             "xsltCompileStepPattern : QName expected\n");
1278                     ctxt->error = 1;
1279                     goto error;
1280                 }
1281                 URI = xsltGetQNameURI(ctxt->elem, &token);
1282                 if (token == NULL) {
1283                     ctxt->error = 1;
1284                     goto error;
1285                 } else {
1286                     name = xmlStrdup(token);
1287                     if (URI != NULL)
1288                         URL = xmlStrdup(URI);
1289                 }
1290                 PUSH(XSLT_OP_CHILD, name, URL);
1291             } else if (xmlStrEqual(token, (const xmlChar *) "attribute")) {
1292                 xmlFree(token);
1293                 token = xsltScanName(ctxt);
1294                 if (token == NULL) {
1295                     xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1296                     xsltGenericError(xsltGenericErrorContext,
1297                             "xsltCompileStepPattern : QName expected\n");
1298                     ctxt->error = 1;
1299                     goto error;
1300                 }
1301                 URI = xsltGetQNameURI(ctxt->elem, &token);
1302                 if (token == NULL) {
1303                     ctxt->error = 1;
1304                     goto error;
1305                 } else {
1306                     name = xmlStrdup(token);
1307                     if (URI != NULL)
1308                         URL = xmlStrdup(URI);
1309                 }
1310                 PUSH(XSLT_OP_ATTR, name, URL);
1311             } else {
1312                 xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1313                 xsltGenericError(xsltGenericErrorContext,
1314                     "xsltCompileStepPattern : 'child' or 'attribute' expected\n");
1315                 ctxt->error = 1;
1316                 goto error;
1317             }
1318             xmlFree(token);
1319         }
1320     } else if (CUR == '*') {
1321         NEXT;
1322         PUSH(XSLT_OP_ALL, token, NULL);
1323     } else {
1324         URI = xsltGetQNameURI(ctxt->elem, &token);
1325         if (token == NULL) {
1326             ctxt->error = 1;
1327             goto error;
1328         }
1329         if (URI != NULL)
1330             URL = xmlStrdup(URI);
1331         PUSH(XSLT_OP_ELEM, token, URL);
1332     }
1333 parse_predicate:
1334     SKIP_BLANKS;
1335     level = 0;
1336     while (CUR == '[') {
1337         const xmlChar *q;
1338         xmlChar *ret = NULL;
1339
1340         level++;
1341         NEXT;
1342         q = CUR_PTR;
1343         /* TODO: avoid breaking in strings ... */
1344         while (CUR != 0) {
1345             /* Skip over nested predicates */
1346             if (CUR == '[')
1347                 level++;
1348             if (CUR == ']') {
1349                 level--;
1350                 if (level == 0)
1351                     break;
1352             }
1353             NEXT;
1354         }
1355         if (CUR == 0) {
1356             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1357             xsltGenericError(xsltGenericErrorContext,
1358                     "xsltCompileStepPattern : ']' expected\n");
1359             ctxt->error = 1;
1360             goto error;
1361         }
1362         ret = xmlStrndup(q, CUR_PTR - q);
1363         PUSH(XSLT_OP_PREDICATE, ret, NULL);
1364         /* push the predicate lower than local test */
1365         SWAP();
1366         NEXT;
1367         SKIP_BLANKS;
1368     }
1369     return;
1370 error:
1371     if (token != NULL)
1372         xmlFree(token);
1373     if (name != NULL)
1374         xmlFree(name);
1375 }
1376
1377 /**
1378  * xsltCompileRelativePathPattern:
1379  * @comp:  the compilation context
1380  * @token:  a posible precompiled name
1381  *
1382  * Compile the XSLT RelativePathPattern and generates a precompiled
1383  * form suitable for fast matching.
1384  *
1385  * [4] RelativePathPattern ::= StepPattern
1386  *                           | RelativePathPattern '/' StepPattern
1387  *                           | RelativePathPattern '//' StepPattern
1388  */
1389 static void
1390 xsltCompileRelativePathPattern(xsltParserContextPtr ctxt, xmlChar *token) {
1391     xsltCompileStepPattern(ctxt, token);
1392     if (ctxt->error)
1393         goto error;
1394     SKIP_BLANKS;
1395     while ((CUR != 0) && (CUR != '|')) {
1396         if ((CUR == '/') && (NXT(1) == '/')) {
1397             PUSH(XSLT_OP_ANCESTOR, NULL, NULL);
1398             NEXT;
1399             NEXT;
1400             SKIP_BLANKS;
1401             xsltCompileStepPattern(ctxt, NULL);
1402         } else if (CUR == '/') {
1403             PUSH(XSLT_OP_PARENT, NULL, NULL);
1404             NEXT;
1405             SKIP_BLANKS;
1406             if ((CUR != 0) || (CUR == '|')) {
1407                 xsltCompileRelativePathPattern(ctxt, NULL);
1408             }
1409         } else {
1410             ctxt->error = 1;
1411         }
1412         if (ctxt->error)
1413             goto error;
1414         SKIP_BLANKS;
1415     }
1416 error:
1417     return;
1418 }
1419
1420 /**
1421  * xsltCompileLocationPathPattern:
1422  * @ctxt:  the compilation context
1423  *
1424  * Compile the XSLT LocationPathPattern and generates a precompiled
1425  * form suitable for fast matching.
1426  *
1427  * [2] LocationPathPattern ::= '/' RelativePathPattern?
1428  *                           | IdKeyPattern (('/' | '//') RelativePathPattern)?
1429  *                           | '//'? RelativePathPattern
1430  */
1431 static void
1432 xsltCompileLocationPathPattern(xsltParserContextPtr ctxt) {
1433     SKIP_BLANKS;
1434     if ((CUR == '/') && (NXT(1) == '/')) {
1435         /*
1436          * since we reverse the query
1437          * a leading // can be safely ignored
1438          */
1439         NEXT;
1440         NEXT;
1441         xsltCompileRelativePathPattern(ctxt, NULL);
1442     } else if (CUR == '/') {
1443         /*
1444          * We need to find root as the parent
1445          */
1446         NEXT;
1447         SKIP_BLANKS;
1448         PUSH(XSLT_OP_ROOT, NULL, NULL);
1449         if ((CUR != 0) || (CUR == '|')) {
1450             PUSH(XSLT_OP_PARENT, NULL, NULL);
1451             xsltCompileRelativePathPattern(ctxt, NULL);
1452         }
1453     } else if (CUR == '*') {
1454         xsltCompileRelativePathPattern(ctxt, NULL);
1455     } else if (CUR == '@') {
1456         xsltCompileRelativePathPattern(ctxt, NULL);
1457     } else {
1458         xmlChar *name;
1459         name = xsltScanName(ctxt);
1460         if (name == NULL) {
1461             xsltPrintErrorContext(NULL, NULL, NULL); /* TODO */
1462             xsltGenericError(xsltGenericErrorContext,
1463                     "xsltCompileLocationPathPattern : Name expected\n");
1464             ctxt->error = 1;
1465             return;
1466         }
1467         SKIP_BLANKS;
1468         if ((CUR == '(') && !xmlXPathIsNodeType(name)) {
1469             xsltCompileIdKeyPattern(ctxt, name, 1);
1470             if ((CUR == '/') && (NXT(1) == '/')) {
1471                 PUSH(XSLT_OP_ANCESTOR, NULL, NULL);
1472                 NEXT;
1473                 NEXT;
1474                 SKIP_BLANKS;
1475                 xsltCompileRelativePathPattern(ctxt, NULL);
1476             } else if (CUR == '/') {
1477                 PUSH(XSLT_OP_PARENT, NULL, NULL);
1478                 NEXT;
1479                 SKIP_BLANKS;
1480                 xsltCompileRelativePathPattern(ctxt, NULL);
1481             }
1482             return;
1483         }
1484         xsltCompileRelativePathPattern(ctxt, name);
1485     }
1486 error:
1487     return;
1488 }
1489
1490 /**
1491  * xsltCompilePattern:
1492  * @pattern: an XSLT pattern
1493  * @doc:  the containing document
1494  * @node:  the containing element
1495  *
1496  * Compile the XSLT pattern and generates a list of precompiled form suitable
1497  * for fast matching.
1498  *
1499  * [1] Pattern ::= LocationPathPattern | Pattern '|' LocationPathPattern
1500  *
1501  * Returns the generated pattern list or NULL in case of failure
1502  */
1503
1504 xsltCompMatchPtr
1505 xsltCompilePattern(const xmlChar *pattern, xmlDocPtr doc, xmlNodePtr node) {
1506     xsltParserContextPtr ctxt = NULL;
1507     xsltCompMatchPtr element, first = NULL, previous = NULL;
1508     int current, start, end;
1509
1510     if (pattern == NULL) {
1511         xsltPrintErrorContext(NULL, NULL, node); /* TODO */
1512         xsltGenericError(xsltGenericErrorContext,
1513                          "xsltCompilePattern : NULL pattern\n");
1514         return(NULL);
1515     }
1516
1517     ctxt = xsltNewParserContext();
1518     if (ctxt == NULL)
1519         return(NULL);
1520     ctxt->doc = doc;
1521     ctxt->elem = node;
1522     current = end = 0;
1523     while (pattern[current] != 0) {
1524         start = current;
1525         while (IS_BLANK(pattern[current]))
1526             current++;
1527         end = current;
1528         while ((pattern[end] != 0) && (pattern[end] != '|'))
1529             end++;
1530         if (current == end) {
1531             xsltPrintErrorContext(NULL, NULL, node); /* TODO */
1532             xsltGenericError(xsltGenericErrorContext,
1533                              "xsltCompilePattern : NULL pattern\n");
1534             goto error;
1535         }
1536         element = xsltNewCompMatch();
1537         if (element == NULL) {
1538             goto error;
1539         }
1540         if (first == NULL)
1541             first = element;
1542         else if (previous != NULL)
1543             previous->next = element;
1544         previous = element;
1545
1546         ctxt->comp = element;
1547         ctxt->base = xmlStrndup(&pattern[start], end - start);
1548         if (ctxt->base == NULL)
1549             goto error;
1550         ctxt->cur = &(ctxt->base)[current - start];
1551         element->pattern = ctxt->base;
1552
1553 #ifdef WITH_XSLT_DEBUG_PATTERN
1554         xsltGenericDebug(xsltGenericDebugContext,
1555                          "xsltCompilePattern : parsing '%s'\n",
1556                          element->pattern);
1557 #endif
1558         xsltCompileLocationPathPattern(ctxt);
1559         if (ctxt->error)
1560             goto error;
1561
1562         /*
1563          * Reverse for faster interpretation.
1564          */
1565         xsltReverseCompMatch(element);
1566
1567         /*
1568          * Set-up the priority
1569          */
1570         if (((element->steps[0].op == XSLT_OP_ELEM) ||
1571              (element->steps[0].op == XSLT_OP_ATTR)) &&
1572             (element->steps[0].value != NULL) &&
1573             (element->steps[1].op == XSLT_OP_END)) {
1574             element->priority = 0;
1575 #if 0
1576         } else if ((element->steps[0].op == XSLT_OP_ROOT) &&
1577                    (element->steps[1].op == XSLT_OP_END)) {
1578             element->priority = 0;
1579 #endif
1580         } else if ((element->steps[0].op == XSLT_OP_PI) &&
1581                    (element->steps[0].value != NULL) &&
1582                    (element->steps[1].op == XSLT_OP_END)) {
1583             element->priority = 0;
1584         } else if ((element->steps[0].op == XSLT_OP_ATTR) &&
1585                    (element->steps[0].value2 != NULL) &&
1586                    (element->steps[1].op == XSLT_OP_END)) {
1587             element->priority = -0.25;
1588         } else if ((element->steps[0].op == XSLT_OP_NS) &&
1589                    (element->steps[0].value != NULL) &&
1590                    (element->steps[1].op == XSLT_OP_END)) {
1591             element->priority = -0.25;
1592         } else if ((element->steps[0].op == XSLT_OP_ATTR) &&
1593                    (element->steps[0].value == NULL) &&
1594                    (element->steps[0].value2 == NULL) &&
1595                    (element->steps[1].op == XSLT_OP_END)) {
1596             element->priority = -0.5;
1597         } else if (((element->steps[0].op == XSLT_OP_PI) ||
1598                     (element->steps[0].op == XSLT_OP_TEXT) ||
1599                     (element->steps[0].op == XSLT_OP_ALL) ||
1600                     (element->steps[0].op == XSLT_OP_NODE) ||
1601                     (element->steps[0].op == XSLT_OP_COMMENT)) &&
1602                    (element->steps[1].op == XSLT_OP_END)) {
1603             element->priority = -0.5;
1604         } else {
1605             element->priority = 0.5;
1606         }
1607 #ifdef WITH_XSLT_DEBUG_PATTERN
1608         xsltGenericDebug(xsltGenericDebugContext,
1609                      "xsltCompilePattern : parsed %s, default priority %f\n",
1610                          element->pattern, element->priority);
1611 #endif
1612         if (pattern[end] == '|')
1613             end++;
1614         current = end;
1615     }
1616     if (end == 0) {
1617         xsltPrintErrorContext(NULL, NULL, node); /* TODO */
1618         xsltGenericError(xsltGenericErrorContext,
1619                          "xsltCompilePattern : NULL pattern\n");
1620         goto error;
1621     }
1622
1623     xsltFreeParserContext(ctxt);
1624     return(first);
1625
1626 error:
1627     if (ctxt != NULL)
1628         xsltFreeParserContext(ctxt);
1629     if (first != NULL)
1630         xsltFreeCompMatchList(first);
1631     return(NULL);
1632 }
1633
1634 /************************************************************************
1635  *                                                                      *
1636  *                      Module interfaces                               *
1637  *                                                                      *
1638  ************************************************************************/
1639
1640 /**
1641  * xsltAddTemplate:
1642  * @style: an XSLT stylesheet
1643  * @cur: an XSLT template
1644  * @mode:  the mode name or NULL
1645  * @modeURI:  the mode URI or NULL
1646  *
1647  * Register the XSLT pattern associated to @cur
1648  *
1649  * Returns -1 in case of error, 0 otherwise
1650  */
1651 int
1652 xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur,
1653                 const xmlChar *mode, const xmlChar *modeURI) {
1654     xsltCompMatchPtr pat, list, *top = NULL, next;
1655     const xmlChar *name = NULL;
1656     float priority;              /* the priority */
1657
1658     if ((style == NULL) || (cur == NULL) || (cur->match == NULL))
1659         return(-1);
1660
1661     priority = cur->priority;
1662     pat = xsltCompilePattern(cur->match, style->doc, cur->elem);
1663     while (pat) {
1664         next = pat->next;
1665         pat->next = NULL;
1666         name = NULL;
1667         
1668         pat->template = cur;
1669         if (mode != NULL)
1670             pat->mode = xmlStrdup(mode);
1671         if (modeURI != NULL)
1672             pat->modeURI = xmlStrdup(modeURI);
1673         if (priority != XSLT_PAT_NO_PRIORITY)
1674             pat->priority = priority;
1675
1676         /*
1677          * insert it in the hash table list corresponding to its lookup name
1678          */
1679         switch (pat->steps[0].op) {
1680         case XSLT_OP_ATTR:
1681             if (pat->steps[0].value != NULL)
1682                 name = pat->steps[0].value;
1683             else
1684                 top = (xsltCompMatchPtr *) &(style->attrMatch);
1685             break;
1686         case XSLT_OP_ELEM:
1687         case XSLT_OP_CHILD:
1688         case XSLT_OP_PARENT:
1689         case XSLT_OP_ANCESTOR:
1690             top = (xsltCompMatchPtr *) &(style->elemMatch);
1691             break;
1692         case XSLT_OP_ROOT:
1693             top = (xsltCompMatchPtr *) &(style->rootMatch);
1694             break;
1695         case XSLT_OP_KEY:
1696             top = (xsltCompMatchPtr *) &(style->keyMatch);
1697             break;
1698         case XSLT_OP_ID:
1699             /* TODO optimize ID !!! */
1700         case XSLT_OP_NS:
1701         case XSLT_OP_ALL:
1702             top = (xsltCompMatchPtr *) &(style->elemMatch);
1703             break;
1704         case XSLT_OP_END:
1705         case XSLT_OP_PREDICATE:
1706             xsltPrintErrorContext(NULL, style, NULL);
1707             xsltGenericError(xsltGenericErrorContext,
1708                              "xsltAddTemplate: invalid compiled pattern\n");
1709             xsltFreeCompMatch(pat);
1710             return(-1);
1711             /*
1712              * TODO: some flags at the top level about type based patterns
1713              *       would be faster than inclusion in the hash table.
1714              */
1715         case XSLT_OP_PI:
1716             if (pat->steps[0].value != NULL)
1717                 name = pat->steps[0].value;
1718             else
1719                 top = (xsltCompMatchPtr *) &(style->piMatch);
1720             break;
1721         case XSLT_OP_COMMENT:
1722             top = (xsltCompMatchPtr *) &(style->commentMatch);
1723             break;
1724         case XSLT_OP_TEXT:
1725             top = (xsltCompMatchPtr *) &(style->textMatch);
1726             break;
1727         case XSLT_OP_NODE:
1728             if (pat->steps[0].value != NULL)
1729                 name = pat->steps[0].value;
1730             else
1731                 top = (xsltCompMatchPtr *) &(style->elemMatch);
1732             
1733             break;
1734         }
1735         if (name != NULL) {
1736             if (style->templatesHash == NULL) {
1737                 style->templatesHash = xmlHashCreate(1024);
1738                 if (style->templatesHash == NULL) {
1739                     xsltFreeCompMatch(pat);
1740                     return(-1);
1741                 }
1742                 xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat);
1743             } else {
1744                 list = (xsltCompMatchPtr) xmlHashLookup3(style->templatesHash,
1745                                                          name, mode, modeURI);
1746                 if (list == NULL) {
1747                     xmlHashAddEntry3(style->templatesHash, name,
1748                                      mode, modeURI, pat);
1749                 } else {
1750                     /*
1751                      * Note '<=' since one must choose among the matching
1752                      * template rules that are left, the one that occurs
1753                      * last in the stylesheet
1754                      */
1755                     if (list->priority <= pat->priority) {
1756                         pat->next = list;
1757                         xmlHashUpdateEntry3(style->templatesHash, name,
1758                                             mode, modeURI, pat, NULL);
1759                     } else {
1760                         while (list->next != NULL) {
1761                             if (list->next->priority <= pat->priority)
1762                                 break;
1763                             list = list->next;
1764                         }
1765                         pat->next = list->next;
1766                         list->next = pat;
1767                     }
1768                 }
1769             }
1770         } else if (top != NULL) {
1771             list = *top;
1772             if (list == NULL) {
1773                 *top = pat;
1774                 pat->next = NULL;
1775             } else if (list->priority <= pat->priority) {
1776                 pat->next = list;
1777                 *top = pat;
1778             } else {
1779                 while (list->next != NULL) {
1780                     if (list->next->priority <= pat->priority)
1781                         break;
1782                     list = list->next;
1783                 }
1784                 pat->next = list->next;
1785                 list->next = pat;
1786             }
1787         } else {
1788             xsltPrintErrorContext(NULL, style, NULL);
1789             xsltGenericError(xsltGenericErrorContext,
1790                              "xsltAddTemplate: invalid compiled pattern\n");
1791             xsltFreeCompMatch(pat);
1792             return(-1);
1793         }
1794 #ifdef WITH_XSLT_DEBUG_PATTERN
1795         if (mode)
1796             xsltGenericDebug(xsltGenericDebugContext,
1797                          "added pattern : '%s' mode '%s' priority %f\n",
1798                              pat->pattern, pat->mode, pat->priority);
1799         else
1800             xsltGenericDebug(xsltGenericDebugContext,
1801                          "added pattern : '%s' priority %f\n",
1802                              pat->pattern, pat->priority);
1803 #endif
1804
1805         pat = next;
1806     }
1807     return(0);
1808 }
1809
1810 /**
1811  * xsltGetTemplate:
1812  * @ctxt:  a XSLT process context
1813  * @node:  the node being processed
1814  * @style:  the current style
1815  *
1816  * Finds the template applying to this node, if @style is non-NULL
1817  * it means one needs to look for the next imported template in scope.
1818  *
1819  * Returns the xsltTemplatePtr or NULL if not found
1820  */
1821 xsltTemplatePtr
1822 xsltGetTemplate(xsltTransformContextPtr ctxt, xmlNodePtr node,
1823                 xsltStylesheetPtr style) {
1824     xsltStylesheetPtr curstyle;
1825     xsltTemplatePtr ret = NULL;
1826     const xmlChar *name = NULL;
1827     xsltCompMatchPtr list = NULL;
1828     float priority;
1829
1830     if ((ctxt == NULL) || (node == NULL))
1831         return(NULL);
1832
1833     if (style == NULL) {
1834         curstyle = ctxt->style;
1835     } else {
1836         curstyle = xsltNextImport(style);
1837     }
1838
1839     while ((curstyle != NULL) && (curstyle != style)) {
1840         priority = XSLT_PAT_NO_PRIORITY;
1841         /* TODO : handle IDs/keys here ! */
1842         if (curstyle->templatesHash != NULL) {
1843             /*
1844              * Use the top name as selector
1845              */
1846             switch (node->type) {
1847                 case XML_ELEMENT_NODE:
1848                 case XML_ATTRIBUTE_NODE:
1849                 case XML_PI_NODE:
1850                     name = node->name;
1851                     break;
1852                 case XML_DOCUMENT_NODE:
1853                 case XML_HTML_DOCUMENT_NODE:
1854                 case XML_TEXT_NODE:
1855                 case XML_CDATA_SECTION_NODE:
1856                 case XML_COMMENT_NODE:
1857                 case XML_ENTITY_REF_NODE:
1858                 case XML_ENTITY_NODE:
1859                 case XML_DOCUMENT_TYPE_NODE:
1860                 case XML_DOCUMENT_FRAG_NODE:
1861                 case XML_NOTATION_NODE:
1862                 case XML_DTD_NODE:
1863                 case XML_ELEMENT_DECL:
1864                 case XML_ATTRIBUTE_DECL:
1865                 case XML_ENTITY_DECL:
1866                 case XML_NAMESPACE_DECL:
1867                 case XML_XINCLUDE_START:
1868                 case XML_XINCLUDE_END:
1869                     break;
1870                 default:
1871                     return(NULL);
1872
1873             }
1874         }
1875         if (name != NULL) {
1876             /*
1877              * find the list of appliable expressions based on the name
1878              */
1879             list = (xsltCompMatchPtr) xmlHashLookup3(curstyle->templatesHash,
1880                                              name, ctxt->mode, ctxt->modeURI);
1881         } else
1882             list = NULL;
1883         while (list != NULL) {
1884             if (xsltTestCompMatch(ctxt, list, node,
1885                                   ctxt->mode, ctxt->modeURI)) {
1886                 ret = list->template;
1887                 priority = list->priority;
1888                 break;
1889             }
1890             list = list->next;
1891         }
1892         list = NULL;
1893
1894         /*
1895          * find alternate generic matches
1896          */
1897         switch (node->type) {
1898             case XML_ELEMENT_NODE:
1899                 list = curstyle->elemMatch;
1900                 break;
1901             case XML_ATTRIBUTE_NODE:
1902                 list = curstyle->attrMatch;
1903                 break;
1904             case XML_PI_NODE:
1905                 list = curstyle->piMatch;
1906                 break;
1907             case XML_DOCUMENT_NODE:
1908             case XML_HTML_DOCUMENT_NODE:
1909                 list = curstyle->rootMatch;
1910                 break;
1911             case XML_TEXT_NODE:
1912             case XML_CDATA_SECTION_NODE:
1913                 list = curstyle->textMatch;
1914                 break;
1915             case XML_COMMENT_NODE:
1916                 list = curstyle->commentMatch;
1917                 break;
1918             case XML_ENTITY_REF_NODE:
1919             case XML_ENTITY_NODE:
1920             case XML_DOCUMENT_TYPE_NODE:
1921             case XML_DOCUMENT_FRAG_NODE:
1922             case XML_NOTATION_NODE:
1923             case XML_DTD_NODE:
1924             case XML_ELEMENT_DECL:
1925             case XML_ATTRIBUTE_DECL:
1926             case XML_ENTITY_DECL:
1927             case XML_NAMESPACE_DECL:
1928             case XML_XINCLUDE_START:
1929             case XML_XINCLUDE_END:
1930                 break;
1931             default:
1932                 break;
1933
1934         }
1935         while ((list != NULL) &&
1936                ((ret == NULL)  || (list->priority > priority))) {
1937             if (xsltTestCompMatch(ctxt, list, node,
1938                                   ctxt->mode, ctxt->modeURI)) {
1939                 ret = list->template;
1940                 priority = list->priority;
1941                 break;
1942             }
1943             list = list->next;
1944         }
1945         /*
1946          * Some of the tests for elements can also apply to documents
1947          */
1948         if ((node->type == XML_DOCUMENT_NODE) ||
1949             (node->type == XML_HTML_DOCUMENT_NODE)) {
1950             list = curstyle->elemMatch;
1951             while ((list != NULL) &&
1952                    ((ret == NULL)  || (list->priority > priority))) {
1953                 if (xsltTestCompMatch(ctxt, list, node,
1954                                       ctxt->mode, ctxt->modeURI)) {
1955                     ret = list->template;
1956                     priority = list->priority;
1957                     break;
1958                 }
1959                 list = list->next;
1960             }
1961         }
1962
1963         if (node->_private != NULL) {
1964             list = curstyle->keyMatch;
1965             while ((list != NULL) &&
1966                    ((ret == NULL)  || (list->priority > priority))) {
1967                 if (xsltTestCompMatch(ctxt, list, node,
1968                                       ctxt->mode, ctxt->modeURI)) {
1969                     ret = list->template;
1970                     priority = list->priority;
1971                     break;
1972                 }
1973                 list = list->next;
1974             }
1975         }
1976         if (ret != NULL)
1977             return(ret);
1978
1979         /*
1980          * Cycle on next curstylesheet import.
1981          */
1982         curstyle = xsltNextImport(curstyle);
1983     }
1984     return(NULL);
1985 }
1986
1987 /**
1988  * xsltCleanupTemplates:
1989  * @style: an XSLT stylesheet
1990  *
1991  * Cleanup the state of the templates used by the stylesheet and
1992  * the ones it imports.
1993  */
1994 void
1995 xsltCleanupTemplates(xsltStylesheetPtr style) {
1996     while (style != NULL) {
1997         xmlHashScan((xmlHashTablePtr) style->templatesHash,
1998                     (xmlHashScanner) xsltCleanupCompMatch, NULL);
1999
2000         style = xsltNextImport(style);
2001     }
2002 }
2003
2004 /**
2005  * xsltFreeTemplateHashes:
2006  * @style: an XSLT stylesheet
2007  *
2008  * Free up the memory used by xsltAddTemplate/xsltGetTemplate mechanism
2009  */
2010 void
2011 xsltFreeTemplateHashes(xsltStylesheetPtr style) {
2012     if (style->templatesHash != NULL)
2013         xmlHashFree((xmlHashTablePtr) style->templatesHash,
2014                     (xmlHashDeallocator) xsltFreeCompMatchList);
2015     if (style->rootMatch != NULL)
2016         xsltFreeCompMatchList(style->rootMatch);
2017     if (style->keyMatch != NULL)
2018         xsltFreeCompMatchList(style->keyMatch);
2019     if (style->elemMatch != NULL)
2020         xsltFreeCompMatchList(style->elemMatch);
2021     if (style->attrMatch != NULL)
2022         xsltFreeCompMatchList(style->attrMatch);
2023     if (style->parentMatch != NULL)
2024         xsltFreeCompMatchList(style->parentMatch);
2025     if (style->textMatch != NULL)
2026         xsltFreeCompMatchList(style->textMatch);
2027     if (style->piMatch != NULL)
2028         xsltFreeCompMatchList(style->piMatch);
2029     if (style->commentMatch != NULL)
2030         xsltFreeCompMatchList(style->commentMatch);
2031 }
2032
2033 #if 0
2034 /**
2035  * xsltMatchPattern
2036  * @node: a node in the source tree
2037  * @pattern: an XSLT pattern
2038  *
2039  * Determine if a node matches a pattern.
2040  */
2041 int
2042 xsltMatchPattern(xsltTransformContextPtr context,
2043                  xmlNodePtr node,
2044                  const xmlChar *pattern)
2045 {
2046     int match = 0;
2047     xsltCompMatchPtr first, comp;
2048
2049     if ((context != NULL) && (pattern != NULL)) {
2050         first = xsltCompilePattern(pattern);
2051         for (comp = first; comp != NULL; comp = comp->next) {
2052             match = xsltTestCompMatch(context, comp, node, NULL, NULL);
2053             if (match)
2054                 break; /* for */
2055         }
2056         if (first)
2057             xsltFreeCompMatchList(first);
2058     }
2059     return match;
2060 }
2061 #endif