Imported Upstream version 2.9.4
[platform/upstream/libxml2.git] / relaxng.c
1 /*
2  * relaxng.c : implementation of the Relax-NG handling and validity checking
3  *
4  * See Copyright for the status of this software.
5  *
6  * Daniel Veillard <veillard@redhat.com>
7  */
8
9 /**
10  * TODO:
11  * - add support for DTD compatibility spec
12  *   http://www.oasis-open.org/committees/relax-ng/compatibility-20011203.html
13  * - report better mem allocations pbms at runtime and abort immediately.
14  */
15
16 #define IN_LIBXML
17 #include "libxml.h"
18
19 #ifdef LIBXML_SCHEMAS_ENABLED
20
21 #include <string.h>
22 #include <stdio.h>
23 #include <libxml/xmlmemory.h>
24 #include <libxml/parser.h>
25 #include <libxml/parserInternals.h>
26 #include <libxml/hash.h>
27 #include <libxml/uri.h>
28
29 #include <libxml/relaxng.h>
30
31 #include <libxml/xmlschemastypes.h>
32 #include <libxml/xmlautomata.h>
33 #include <libxml/xmlregexp.h>
34 #include <libxml/xmlschemastypes.h>
35
36 /*
37  * The Relax-NG namespace
38  */
39 static const xmlChar *xmlRelaxNGNs = (const xmlChar *)
40     "http://relaxng.org/ns/structure/1.0";
41
42 #define IS_RELAXNG(node, typ)                                           \
43    ((node != NULL) && (node->ns != NULL) &&                             \
44     (node->type == XML_ELEMENT_NODE) &&                                 \
45     (xmlStrEqual(node->name, (const xmlChar *) typ)) &&         \
46     (xmlStrEqual(node->ns->href, xmlRelaxNGNs)))
47
48
49 #if 0
50 #define DEBUG 1
51
52 #define DEBUG_GRAMMAR 1
53
54 #define DEBUG_CONTENT 1
55
56 #define DEBUG_TYPE 1
57
58 #define DEBUG_VALID 1
59
60 #define DEBUG_INTERLEAVE 1
61
62 #define DEBUG_LIST 1
63
64 #define DEBUG_INCLUDE 1
65
66 #define DEBUG_ERROR 1
67
68 #define DEBUG_COMPILE 1
69
70 #define DEBUG_PROGRESSIVE 1
71 #endif
72
73 #define MAX_ERROR 5
74
75 #define TODO                                                            \
76     xmlGenericError(xmlGenericErrorContext,                             \
77             "Unimplemented block at %s:%d\n",                           \
78             __FILE__, __LINE__);
79
80 typedef struct _xmlRelaxNGSchema xmlRelaxNGSchema;
81 typedef xmlRelaxNGSchema *xmlRelaxNGSchemaPtr;
82
83 typedef struct _xmlRelaxNGDefine xmlRelaxNGDefine;
84 typedef xmlRelaxNGDefine *xmlRelaxNGDefinePtr;
85
86 typedef struct _xmlRelaxNGDocument xmlRelaxNGDocument;
87 typedef xmlRelaxNGDocument *xmlRelaxNGDocumentPtr;
88
89 typedef struct _xmlRelaxNGInclude xmlRelaxNGInclude;
90 typedef xmlRelaxNGInclude *xmlRelaxNGIncludePtr;
91
92 typedef enum {
93     XML_RELAXNG_COMBINE_UNDEFINED = 0,  /* undefined */
94     XML_RELAXNG_COMBINE_CHOICE, /* choice */
95     XML_RELAXNG_COMBINE_INTERLEAVE      /* interleave */
96 } xmlRelaxNGCombine;
97
98 typedef enum {
99     XML_RELAXNG_CONTENT_ERROR = -1,
100     XML_RELAXNG_CONTENT_EMPTY = 0,
101     XML_RELAXNG_CONTENT_SIMPLE,
102     XML_RELAXNG_CONTENT_COMPLEX
103 } xmlRelaxNGContentType;
104
105 typedef struct _xmlRelaxNGGrammar xmlRelaxNGGrammar;
106 typedef xmlRelaxNGGrammar *xmlRelaxNGGrammarPtr;
107
108 struct _xmlRelaxNGGrammar {
109     xmlRelaxNGGrammarPtr parent;        /* the parent grammar if any */
110     xmlRelaxNGGrammarPtr children;      /* the children grammar if any */
111     xmlRelaxNGGrammarPtr next;  /* the next grammar if any */
112     xmlRelaxNGDefinePtr start;  /* <start> content */
113     xmlRelaxNGCombine combine;  /* the default combine value */
114     xmlRelaxNGDefinePtr startList;      /* list of <start> definitions */
115     xmlHashTablePtr defs;       /* define* */
116     xmlHashTablePtr refs;       /* references */
117 };
118
119
120 typedef enum {
121     XML_RELAXNG_NOOP = -1,      /* a no operation from simplification  */
122     XML_RELAXNG_EMPTY = 0,      /* an empty pattern */
123     XML_RELAXNG_NOT_ALLOWED,    /* not allowed top */
124     XML_RELAXNG_EXCEPT,         /* except present in nameclass defs */
125     XML_RELAXNG_TEXT,           /* textual content */
126     XML_RELAXNG_ELEMENT,        /* an element */
127     XML_RELAXNG_DATATYPE,       /* extenal data type definition */
128     XML_RELAXNG_PARAM,          /* extenal data type parameter */
129     XML_RELAXNG_VALUE,          /* value from an extenal data type definition */
130     XML_RELAXNG_LIST,           /* a list of patterns */
131     XML_RELAXNG_ATTRIBUTE,      /* an attrbute following a pattern */
132     XML_RELAXNG_DEF,            /* a definition */
133     XML_RELAXNG_REF,            /* reference to a definition */
134     XML_RELAXNG_EXTERNALREF,    /* reference to an external def */
135     XML_RELAXNG_PARENTREF,      /* reference to a def in the parent grammar */
136     XML_RELAXNG_OPTIONAL,       /* optional patterns */
137     XML_RELAXNG_ZEROORMORE,     /* zero or more non empty patterns */
138     XML_RELAXNG_ONEORMORE,      /* one or more non empty patterns */
139     XML_RELAXNG_CHOICE,         /* a choice between non empty patterns */
140     XML_RELAXNG_GROUP,          /* a pair/group of non empty patterns */
141     XML_RELAXNG_INTERLEAVE,     /* interleaving choice of non-empty patterns */
142     XML_RELAXNG_START           /* Used to keep track of starts on grammars */
143 } xmlRelaxNGType;
144
145 #define IS_NULLABLE             (1 << 0)
146 #define IS_NOT_NULLABLE         (1 << 1)
147 #define IS_INDETERMINIST        (1 << 2)
148 #define IS_MIXED                (1 << 3)
149 #define IS_TRIABLE              (1 << 4)
150 #define IS_PROCESSED            (1 << 5)
151 #define IS_COMPILABLE           (1 << 6)
152 #define IS_NOT_COMPILABLE       (1 << 7)
153 #define IS_EXTERNAL_REF         (1 << 8)
154
155 struct _xmlRelaxNGDefine {
156     xmlRelaxNGType type;        /* the type of definition */
157     xmlNodePtr node;            /* the node in the source */
158     xmlChar *name;              /* the element local name if present */
159     xmlChar *ns;                /* the namespace local name if present */
160     xmlChar *value;             /* value when available */
161     void *data;                 /* data lib or specific pointer */
162     xmlRelaxNGDefinePtr content;        /* the expected content */
163     xmlRelaxNGDefinePtr parent; /* the parent definition, if any */
164     xmlRelaxNGDefinePtr next;   /* list within grouping sequences */
165     xmlRelaxNGDefinePtr attrs;  /* list of attributes for elements */
166     xmlRelaxNGDefinePtr nameClass;      /* the nameClass definition if any */
167     xmlRelaxNGDefinePtr nextHash;       /* next define in defs/refs hash tables */
168     short depth;                /* used for the cycle detection */
169     short dflags;               /* define related flags */
170     xmlRegexpPtr contModel;     /* a compiled content model if available */
171 };
172
173 /**
174  * _xmlRelaxNG:
175  *
176  * A RelaxNGs definition
177  */
178 struct _xmlRelaxNG {
179     void *_private;             /* unused by the library for users or bindings */
180     xmlRelaxNGGrammarPtr topgrammar;
181     xmlDocPtr doc;
182
183     int idref;                  /* requires idref checking */
184
185     xmlHashTablePtr defs;       /* define */
186     xmlHashTablePtr refs;       /* references */
187     xmlRelaxNGDocumentPtr documents;    /* all the documents loaded */
188     xmlRelaxNGIncludePtr includes;      /* all the includes loaded */
189     int defNr;                  /* number of defines used */
190     xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
191
192 };
193
194 #define XML_RELAXNG_IN_ATTRIBUTE        (1 << 0)
195 #define XML_RELAXNG_IN_ONEORMORE        (1 << 1)
196 #define XML_RELAXNG_IN_LIST             (1 << 2)
197 #define XML_RELAXNG_IN_DATAEXCEPT       (1 << 3)
198 #define XML_RELAXNG_IN_START            (1 << 4)
199 #define XML_RELAXNG_IN_OOMGROUP         (1 << 5)
200 #define XML_RELAXNG_IN_OOMINTERLEAVE    (1 << 6)
201 #define XML_RELAXNG_IN_EXTERNALREF      (1 << 7)
202 #define XML_RELAXNG_IN_ANYEXCEPT        (1 << 8)
203 #define XML_RELAXNG_IN_NSEXCEPT         (1 << 9)
204
205 struct _xmlRelaxNGParserCtxt {
206     void *userData;             /* user specific data block */
207     xmlRelaxNGValidityErrorFunc error;  /* the callback in case of errors */
208     xmlRelaxNGValidityWarningFunc warning;      /* the callback in case of warning */
209     xmlStructuredErrorFunc serror;
210     xmlRelaxNGValidErr err;
211
212     xmlRelaxNGPtr schema;       /* The schema in use */
213     xmlRelaxNGGrammarPtr grammar;       /* the current grammar */
214     xmlRelaxNGGrammarPtr parentgrammar; /* the parent grammar */
215     int flags;                  /* parser flags */
216     int nbErrors;               /* number of errors at parse time */
217     int nbWarnings;             /* number of warnings at parse time */
218     const xmlChar *define;      /* the current define scope */
219     xmlRelaxNGDefinePtr def;    /* the current define */
220
221     int nbInterleaves;
222     xmlHashTablePtr interleaves;        /* keep track of all the interleaves */
223
224     xmlRelaxNGDocumentPtr documents;    /* all the documents loaded */
225     xmlRelaxNGIncludePtr includes;      /* all the includes loaded */
226     xmlChar *URL;
227     xmlDocPtr document;
228
229     int defNr;                  /* number of defines used */
230     int defMax;                 /* number of defines aloocated */
231     xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
232
233     const char *buffer;
234     int size;
235
236     /* the document stack */
237     xmlRelaxNGDocumentPtr doc;  /* Current parsed external ref */
238     int docNr;                  /* Depth of the parsing stack */
239     int docMax;                 /* Max depth of the parsing stack */
240     xmlRelaxNGDocumentPtr *docTab;      /* array of docs */
241
242     /* the include stack */
243     xmlRelaxNGIncludePtr inc;   /* Current parsed include */
244     int incNr;                  /* Depth of the include parsing stack */
245     int incMax;                 /* Max depth of the parsing stack */
246     xmlRelaxNGIncludePtr *incTab;       /* array of incs */
247
248     int idref;                  /* requires idref checking */
249
250     /* used to compile content models */
251     xmlAutomataPtr am;          /* the automata */
252     xmlAutomataStatePtr state;  /* used to build the automata */
253
254     int crng;                   /* compact syntax and other flags */
255     int freedoc;                /* need to free the document */
256 };
257
258 #define FLAGS_IGNORABLE         1
259 #define FLAGS_NEGATIVE          2
260 #define FLAGS_MIXED_CONTENT     4
261 #define FLAGS_NOERROR           8
262
263 /**
264  * xmlRelaxNGInterleaveGroup:
265  *
266  * A RelaxNGs partition set associated to lists of definitions
267  */
268 typedef struct _xmlRelaxNGInterleaveGroup xmlRelaxNGInterleaveGroup;
269 typedef xmlRelaxNGInterleaveGroup *xmlRelaxNGInterleaveGroupPtr;
270 struct _xmlRelaxNGInterleaveGroup {
271     xmlRelaxNGDefinePtr rule;   /* the rule to satisfy */
272     xmlRelaxNGDefinePtr *defs;  /* the array of element definitions */
273     xmlRelaxNGDefinePtr *attrs; /* the array of attributes definitions */
274 };
275
276 #define IS_DETERMINIST          1
277 #define IS_NEEDCHECK            2
278
279 /**
280  * xmlRelaxNGPartitions:
281  *
282  * A RelaxNGs partition associated to an interleave group
283  */
284 typedef struct _xmlRelaxNGPartition xmlRelaxNGPartition;
285 typedef xmlRelaxNGPartition *xmlRelaxNGPartitionPtr;
286 struct _xmlRelaxNGPartition {
287     int nbgroups;               /* number of groups in the partitions */
288     xmlHashTablePtr triage;     /* hash table used to direct nodes to the
289                                  * right group when possible */
290     int flags;                  /* determinist ? */
291     xmlRelaxNGInterleaveGroupPtr *groups;
292 };
293
294 /**
295  * xmlRelaxNGValidState:
296  *
297  * A RelaxNGs validation state
298  */
299 #define MAX_ATTR 20
300 typedef struct _xmlRelaxNGValidState xmlRelaxNGValidState;
301 typedef xmlRelaxNGValidState *xmlRelaxNGValidStatePtr;
302 struct _xmlRelaxNGValidState {
303     xmlNodePtr node;            /* the current node */
304     xmlNodePtr seq;             /* the sequence of children left to validate */
305     int nbAttrs;                /* the number of attributes */
306     int maxAttrs;               /* the size of attrs */
307     int nbAttrLeft;             /* the number of attributes left to validate */
308     xmlChar *value;             /* the value when operating on string */
309     xmlChar *endvalue;          /* the end value when operating on string */
310     xmlAttrPtr *attrs;          /* the array of attributes */
311 };
312
313 /**
314  * xmlRelaxNGStates:
315  *
316  * A RelaxNGs container for validation state
317  */
318 typedef struct _xmlRelaxNGStates xmlRelaxNGStates;
319 typedef xmlRelaxNGStates *xmlRelaxNGStatesPtr;
320 struct _xmlRelaxNGStates {
321     int nbState;                /* the number of states */
322     int maxState;               /* the size of the array */
323     xmlRelaxNGValidStatePtr *tabState;
324 };
325
326 #define ERROR_IS_DUP    1
327
328 /**
329  * xmlRelaxNGValidError:
330  *
331  * A RelaxNGs validation error
332  */
333 typedef struct _xmlRelaxNGValidError xmlRelaxNGValidError;
334 typedef xmlRelaxNGValidError *xmlRelaxNGValidErrorPtr;
335 struct _xmlRelaxNGValidError {
336     xmlRelaxNGValidErr err;     /* the error number */
337     int flags;                  /* flags */
338     xmlNodePtr node;            /* the current node */
339     xmlNodePtr seq;             /* the current child */
340     const xmlChar *arg1;        /* first arg */
341     const xmlChar *arg2;        /* second arg */
342 };
343
344 /**
345  * xmlRelaxNGValidCtxt:
346  *
347  * A RelaxNGs validation context
348  */
349
350 struct _xmlRelaxNGValidCtxt {
351     void *userData;             /* user specific data block */
352     xmlRelaxNGValidityErrorFunc error;  /* the callback in case of errors */
353     xmlRelaxNGValidityWarningFunc warning;      /* the callback in case of warning */
354     xmlStructuredErrorFunc serror;
355     int nbErrors;               /* number of errors in validation */
356
357     xmlRelaxNGPtr schema;       /* The schema in use */
358     xmlDocPtr doc;              /* the document being validated */
359     int flags;                  /* validation flags */
360     int depth;                  /* validation depth */
361     int idref;                  /* requires idref checking */
362     int errNo;                  /* the first error found */
363
364     /*
365      * Errors accumulated in branches may have to be stacked to be
366      * provided back when it's sure they affect validation.
367      */
368     xmlRelaxNGValidErrorPtr err;        /* Last error */
369     int errNr;                  /* Depth of the error stack */
370     int errMax;                 /* Max depth of the error stack */
371     xmlRelaxNGValidErrorPtr errTab;     /* stack of errors */
372
373     xmlRelaxNGValidStatePtr state;      /* the current validation state */
374     xmlRelaxNGStatesPtr states; /* the accumulated state list */
375
376     xmlRelaxNGStatesPtr freeState;      /* the pool of free valid states */
377     int freeStatesNr;
378     int freeStatesMax;
379     xmlRelaxNGStatesPtr *freeStates;    /* the pool of free state groups */
380
381     /*
382      * This is used for "progressive" validation
383      */
384     xmlRegExecCtxtPtr elem;     /* the current element regexp */
385     int elemNr;                 /* the number of element validated */
386     int elemMax;                /* the max depth of elements */
387     xmlRegExecCtxtPtr *elemTab; /* the stack of regexp runtime */
388     int pstate;                 /* progressive state */
389     xmlNodePtr pnode;           /* the current node */
390     xmlRelaxNGDefinePtr pdef;   /* the non-streamable definition */
391     int perr;                   /* signal error in content model
392                                  * outside the regexp */
393 };
394
395 /**
396  * xmlRelaxNGInclude:
397  *
398  * Structure associated to a RelaxNGs document element
399  */
400 struct _xmlRelaxNGInclude {
401     xmlRelaxNGIncludePtr next;  /* keep a chain of includes */
402     xmlChar *href;              /* the normalized href value */
403     xmlDocPtr doc;              /* the associated XML document */
404     xmlRelaxNGDefinePtr content;        /* the definitions */
405     xmlRelaxNGPtr schema;       /* the schema */
406 };
407
408 /**
409  * xmlRelaxNGDocument:
410  *
411  * Structure associated to a RelaxNGs document element
412  */
413 struct _xmlRelaxNGDocument {
414     xmlRelaxNGDocumentPtr next; /* keep a chain of documents */
415     xmlChar *href;              /* the normalized href value */
416     xmlDocPtr doc;              /* the associated XML document */
417     xmlRelaxNGDefinePtr content;        /* the definitions */
418     xmlRelaxNGPtr schema;       /* the schema */
419     int externalRef;            /* 1 if an external ref */
420 };
421
422
423 /************************************************************************
424  *                                                                      *
425  *              Some factorized error routines                          *
426  *                                                                      *
427  ************************************************************************/
428
429 /**
430  * xmlRngPErrMemory:
431  * @ctxt:  an Relax-NG parser context
432  * @extra:  extra informations
433  *
434  * Handle a redefinition of attribute error
435  */
436 static void
437 xmlRngPErrMemory(xmlRelaxNGParserCtxtPtr ctxt, const char *extra)
438 {
439     xmlStructuredErrorFunc schannel = NULL;
440     xmlGenericErrorFunc channel = NULL;
441     void *data = NULL;
442
443     if (ctxt != NULL) {
444         if (ctxt->serror != NULL)
445             schannel = ctxt->serror;
446         else
447             channel = ctxt->error;
448         data = ctxt->userData;
449         ctxt->nbErrors++;
450     }
451     if (extra)
452         __xmlRaiseError(schannel, channel, data,
453                         NULL, NULL, XML_FROM_RELAXNGP,
454                         XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
455                         NULL, NULL, 0, 0,
456                         "Memory allocation failed : %s\n", extra);
457     else
458         __xmlRaiseError(schannel, channel, data,
459                         NULL, NULL, XML_FROM_RELAXNGP,
460                         XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, NULL,
461                         NULL, NULL, 0, 0, "Memory allocation failed\n");
462 }
463
464 /**
465  * xmlRngVErrMemory:
466  * @ctxt:  a Relax-NG validation context
467  * @extra:  extra informations
468  *
469  * Handle a redefinition of attribute error
470  */
471 static void
472 xmlRngVErrMemory(xmlRelaxNGValidCtxtPtr ctxt, const char *extra)
473 {
474     xmlStructuredErrorFunc schannel = NULL;
475     xmlGenericErrorFunc channel = NULL;
476     void *data = NULL;
477
478     if (ctxt != NULL) {
479         if (ctxt->serror != NULL)
480             schannel = ctxt->serror;
481         else
482             channel = ctxt->error;
483         data = ctxt->userData;
484         ctxt->nbErrors++;
485     }
486     if (extra)
487         __xmlRaiseError(schannel, channel, data,
488                         NULL, NULL, XML_FROM_RELAXNGV,
489                         XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
490                         NULL, NULL, 0, 0,
491                         "Memory allocation failed : %s\n", extra);
492     else
493         __xmlRaiseError(schannel, channel, data,
494                         NULL, NULL, XML_FROM_RELAXNGV,
495                         XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, NULL,
496                         NULL, NULL, 0, 0, "Memory allocation failed\n");
497 }
498
499 /**
500  * xmlRngPErr:
501  * @ctxt:  a Relax-NG parser context
502  * @node:  the node raising the error
503  * @error:  the error code
504  * @msg:  message
505  * @str1:  extra info
506  * @str2:  extra info
507  *
508  * Handle a Relax NG Parsing error
509  */
510 static void LIBXML_ATTR_FORMAT(4,0)
511 xmlRngPErr(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node, int error,
512            const char *msg, const xmlChar * str1, const xmlChar * str2)
513 {
514     xmlStructuredErrorFunc schannel = NULL;
515     xmlGenericErrorFunc channel = NULL;
516     void *data = NULL;
517
518     if (ctxt != NULL) {
519         if (ctxt->serror != NULL)
520             schannel = ctxt->serror;
521         else
522             channel = ctxt->error;
523         data = ctxt->userData;
524         ctxt->nbErrors++;
525     }
526     __xmlRaiseError(schannel, channel, data,
527                     NULL, node, XML_FROM_RELAXNGP,
528                     error, XML_ERR_ERROR, NULL, 0,
529                     (const char *) str1, (const char *) str2, NULL, 0, 0,
530                     msg, str1, str2);
531 }
532
533 /**
534  * xmlRngVErr:
535  * @ctxt:  a Relax-NG validation context
536  * @node:  the node raising the error
537  * @error:  the error code
538  * @msg:  message
539  * @str1:  extra info
540  * @str2:  extra info
541  *
542  * Handle a Relax NG Validation error
543  */
544 static void LIBXML_ATTR_FORMAT(4,0)
545 xmlRngVErr(xmlRelaxNGValidCtxtPtr ctxt, xmlNodePtr node, int error,
546            const char *msg, const xmlChar * str1, const xmlChar * str2)
547 {
548     xmlStructuredErrorFunc schannel = NULL;
549     xmlGenericErrorFunc channel = NULL;
550     void *data = NULL;
551
552     if (ctxt != NULL) {
553         if (ctxt->serror != NULL)
554             schannel = ctxt->serror;
555         else
556             channel = ctxt->error;
557         data = ctxt->userData;
558         ctxt->nbErrors++;
559     }
560     __xmlRaiseError(schannel, channel, data,
561                     NULL, node, XML_FROM_RELAXNGV,
562                     error, XML_ERR_ERROR, NULL, 0,
563                     (const char *) str1, (const char *) str2, NULL, 0, 0,
564                     msg, str1, str2);
565 }
566
567 /************************************************************************
568  *                                                                      *
569  *              Preliminary type checking interfaces                    *
570  *                                                                      *
571  ************************************************************************/
572
573 /**
574  * xmlRelaxNGTypeHave:
575  * @data:  data needed for the library
576  * @type:  the type name
577  * @value:  the value to check
578  *
579  * Function provided by a type library to check if a type is exported
580  *
581  * Returns 1 if yes, 0 if no and -1 in case of error.
582  */
583 typedef int (*xmlRelaxNGTypeHave) (void *data, const xmlChar * type);
584
585 /**
586  * xmlRelaxNGTypeCheck:
587  * @data:  data needed for the library
588  * @type:  the type name
589  * @value:  the value to check
590  * @result:  place to store the result if needed
591  *
592  * Function provided by a type library to check if a value match a type
593  *
594  * Returns 1 if yes, 0 if no and -1 in case of error.
595  */
596 typedef int (*xmlRelaxNGTypeCheck) (void *data, const xmlChar * type,
597                                     const xmlChar * value, void **result,
598                                     xmlNodePtr node);
599
600 /**
601  * xmlRelaxNGFacetCheck:
602  * @data:  data needed for the library
603  * @type:  the type name
604  * @facet:  the facet name
605  * @val:  the facet value
606  * @strval:  the string value
607  * @value:  the value to check
608  *
609  * Function provided by a type library to check a value facet
610  *
611  * Returns 1 if yes, 0 if no and -1 in case of error.
612  */
613 typedef int (*xmlRelaxNGFacetCheck) (void *data, const xmlChar * type,
614                                      const xmlChar * facet,
615                                      const xmlChar * val,
616                                      const xmlChar * strval, void *value);
617
618 /**
619  * xmlRelaxNGTypeFree:
620  * @data:  data needed for the library
621  * @result:  the value to free
622  *
623  * Function provided by a type library to free a returned result
624  */
625 typedef void (*xmlRelaxNGTypeFree) (void *data, void *result);
626
627 /**
628  * xmlRelaxNGTypeCompare:
629  * @data:  data needed for the library
630  * @type:  the type name
631  * @value1:  the first value
632  * @value2:  the second value
633  *
634  * Function provided by a type library to compare two values accordingly
635  * to a type.
636  *
637  * Returns 1 if yes, 0 if no and -1 in case of error.
638  */
639 typedef int (*xmlRelaxNGTypeCompare) (void *data, const xmlChar * type,
640                                       const xmlChar * value1,
641                                       xmlNodePtr ctxt1,
642                                       void *comp1,
643                                       const xmlChar * value2,
644                                       xmlNodePtr ctxt2);
645 typedef struct _xmlRelaxNGTypeLibrary xmlRelaxNGTypeLibrary;
646 typedef xmlRelaxNGTypeLibrary *xmlRelaxNGTypeLibraryPtr;
647 struct _xmlRelaxNGTypeLibrary {
648     const xmlChar *namespace;   /* the datatypeLibrary value */
649     void *data;                 /* data needed for the library */
650     xmlRelaxNGTypeHave have;    /* the export function */
651     xmlRelaxNGTypeCheck check;  /* the checking function */
652     xmlRelaxNGTypeCompare comp; /* the compare function */
653     xmlRelaxNGFacetCheck facet; /* the facet check function */
654     xmlRelaxNGTypeFree freef;   /* the freeing function */
655 };
656
657 /************************************************************************
658  *                                                                      *
659  *                      Allocation functions                            *
660  *                                                                      *
661  ************************************************************************/
662 static void xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar);
663 static void xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define);
664 static void xmlRelaxNGNormExtSpace(xmlChar * value);
665 static void xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema);
666 static int xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt
667                                      ATTRIBUTE_UNUSED,
668                                      xmlRelaxNGValidStatePtr state1,
669                                      xmlRelaxNGValidStatePtr state2);
670 static void xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,
671                                      xmlRelaxNGValidStatePtr state);
672
673 /**
674  * xmlRelaxNGFreeDocument:
675  * @docu:  a document structure
676  *
677  * Deallocate a RelaxNG document structure.
678  */
679 static void
680 xmlRelaxNGFreeDocument(xmlRelaxNGDocumentPtr docu)
681 {
682     if (docu == NULL)
683         return;
684
685     if (docu->href != NULL)
686         xmlFree(docu->href);
687     if (docu->doc != NULL)
688         xmlFreeDoc(docu->doc);
689     if (docu->schema != NULL)
690         xmlRelaxNGFreeInnerSchema(docu->schema);
691     xmlFree(docu);
692 }
693
694 /**
695  * xmlRelaxNGFreeDocumentList:
696  * @docu:  a list of  document structure
697  *
698  * Deallocate a RelaxNG document structures.
699  */
700 static void
701 xmlRelaxNGFreeDocumentList(xmlRelaxNGDocumentPtr docu)
702 {
703     xmlRelaxNGDocumentPtr next;
704
705     while (docu != NULL) {
706         next = docu->next;
707         xmlRelaxNGFreeDocument(docu);
708         docu = next;
709     }
710 }
711
712 /**
713  * xmlRelaxNGFreeInclude:
714  * @incl:  a include structure
715  *
716  * Deallocate a RelaxNG include structure.
717  */
718 static void
719 xmlRelaxNGFreeInclude(xmlRelaxNGIncludePtr incl)
720 {
721     if (incl == NULL)
722         return;
723
724     if (incl->href != NULL)
725         xmlFree(incl->href);
726     if (incl->doc != NULL)
727         xmlFreeDoc(incl->doc);
728     if (incl->schema != NULL)
729         xmlRelaxNGFree(incl->schema);
730     xmlFree(incl);
731 }
732
733 /**
734  * xmlRelaxNGFreeIncludeList:
735  * @incl:  a include structure list
736  *
737  * Deallocate a RelaxNG include structure.
738  */
739 static void
740 xmlRelaxNGFreeIncludeList(xmlRelaxNGIncludePtr incl)
741 {
742     xmlRelaxNGIncludePtr next;
743
744     while (incl != NULL) {
745         next = incl->next;
746         xmlRelaxNGFreeInclude(incl);
747         incl = next;
748     }
749 }
750
751 /**
752  * xmlRelaxNGNewRelaxNG:
753  * @ctxt:  a Relax-NG validation context (optional)
754  *
755  * Allocate a new RelaxNG structure.
756  *
757  * Returns the newly allocated structure or NULL in case or error
758  */
759 static xmlRelaxNGPtr
760 xmlRelaxNGNewRelaxNG(xmlRelaxNGParserCtxtPtr ctxt)
761 {
762     xmlRelaxNGPtr ret;
763
764     ret = (xmlRelaxNGPtr) xmlMalloc(sizeof(xmlRelaxNG));
765     if (ret == NULL) {
766         xmlRngPErrMemory(ctxt, NULL);
767         return (NULL);
768     }
769     memset(ret, 0, sizeof(xmlRelaxNG));
770
771     return (ret);
772 }
773
774 /**
775  * xmlRelaxNGFreeInnerSchema:
776  * @schema:  a schema structure
777  *
778  * Deallocate a RelaxNG schema structure.
779  */
780 static void
781 xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema)
782 {
783     if (schema == NULL)
784         return;
785
786     if (schema->doc != NULL)
787         xmlFreeDoc(schema->doc);
788     if (schema->defTab != NULL) {
789         int i;
790
791         for (i = 0; i < schema->defNr; i++)
792             xmlRelaxNGFreeDefine(schema->defTab[i]);
793         xmlFree(schema->defTab);
794     }
795
796     xmlFree(schema);
797 }
798
799 /**
800  * xmlRelaxNGFree:
801  * @schema:  a schema structure
802  *
803  * Deallocate a RelaxNG structure.
804  */
805 void
806 xmlRelaxNGFree(xmlRelaxNGPtr schema)
807 {
808     if (schema == NULL)
809         return;
810
811     if (schema->topgrammar != NULL)
812         xmlRelaxNGFreeGrammar(schema->topgrammar);
813     if (schema->doc != NULL)
814         xmlFreeDoc(schema->doc);
815     if (schema->documents != NULL)
816         xmlRelaxNGFreeDocumentList(schema->documents);
817     if (schema->includes != NULL)
818         xmlRelaxNGFreeIncludeList(schema->includes);
819     if (schema->defTab != NULL) {
820         int i;
821
822         for (i = 0; i < schema->defNr; i++)
823             xmlRelaxNGFreeDefine(schema->defTab[i]);
824         xmlFree(schema->defTab);
825     }
826
827     xmlFree(schema);
828 }
829
830 /**
831  * xmlRelaxNGNewGrammar:
832  * @ctxt:  a Relax-NG validation context (optional)
833  *
834  * Allocate a new RelaxNG grammar.
835  *
836  * Returns the newly allocated structure or NULL in case or error
837  */
838 static xmlRelaxNGGrammarPtr
839 xmlRelaxNGNewGrammar(xmlRelaxNGParserCtxtPtr ctxt)
840 {
841     xmlRelaxNGGrammarPtr ret;
842
843     ret = (xmlRelaxNGGrammarPtr) xmlMalloc(sizeof(xmlRelaxNGGrammar));
844     if (ret == NULL) {
845         xmlRngPErrMemory(ctxt, NULL);
846         return (NULL);
847     }
848     memset(ret, 0, sizeof(xmlRelaxNGGrammar));
849
850     return (ret);
851 }
852
853 /**
854  * xmlRelaxNGFreeGrammar:
855  * @grammar:  a grammar structure
856  *
857  * Deallocate a RelaxNG grammar structure.
858  */
859 static void
860 xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar)
861 {
862     if (grammar == NULL)
863         return;
864
865     if (grammar->children != NULL) {
866         xmlRelaxNGFreeGrammar(grammar->children);
867     }
868     if (grammar->next != NULL) {
869         xmlRelaxNGFreeGrammar(grammar->next);
870     }
871     if (grammar->refs != NULL) {
872         xmlHashFree(grammar->refs, NULL);
873     }
874     if (grammar->defs != NULL) {
875         xmlHashFree(grammar->defs, NULL);
876     }
877
878     xmlFree(grammar);
879 }
880
881 /**
882  * xmlRelaxNGNewDefine:
883  * @ctxt:  a Relax-NG validation context
884  * @node:  the node in the input document.
885  *
886  * Allocate a new RelaxNG define.
887  *
888  * Returns the newly allocated structure or NULL in case or error
889  */
890 static xmlRelaxNGDefinePtr
891 xmlRelaxNGNewDefine(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
892 {
893     xmlRelaxNGDefinePtr ret;
894
895     if (ctxt->defMax == 0) {
896         ctxt->defMax = 16;
897         ctxt->defNr = 0;
898         ctxt->defTab = (xmlRelaxNGDefinePtr *)
899             xmlMalloc(ctxt->defMax * sizeof(xmlRelaxNGDefinePtr));
900         if (ctxt->defTab == NULL) {
901             xmlRngPErrMemory(ctxt, "allocating define\n");
902             return (NULL);
903         }
904     } else if (ctxt->defMax <= ctxt->defNr) {
905         xmlRelaxNGDefinePtr *tmp;
906
907         ctxt->defMax *= 2;
908         tmp = (xmlRelaxNGDefinePtr *) xmlRealloc(ctxt->defTab,
909                                                  ctxt->defMax *
910                                                  sizeof
911                                                  (xmlRelaxNGDefinePtr));
912         if (tmp == NULL) {
913             xmlRngPErrMemory(ctxt, "allocating define\n");
914             return (NULL);
915         }
916         ctxt->defTab = tmp;
917     }
918     ret = (xmlRelaxNGDefinePtr) xmlMalloc(sizeof(xmlRelaxNGDefine));
919     if (ret == NULL) {
920         xmlRngPErrMemory(ctxt, "allocating define\n");
921         return (NULL);
922     }
923     memset(ret, 0, sizeof(xmlRelaxNGDefine));
924     ctxt->defTab[ctxt->defNr++] = ret;
925     ret->node = node;
926     ret->depth = -1;
927     return (ret);
928 }
929
930 /**
931  * xmlRelaxNGFreePartition:
932  * @partitions:  a partition set structure
933  *
934  * Deallocate RelaxNG partition set structures.
935  */
936 static void
937 xmlRelaxNGFreePartition(xmlRelaxNGPartitionPtr partitions)
938 {
939     xmlRelaxNGInterleaveGroupPtr group;
940     int j;
941
942     if (partitions != NULL) {
943         if (partitions->groups != NULL) {
944             for (j = 0; j < partitions->nbgroups; j++) {
945                 group = partitions->groups[j];
946                 if (group != NULL) {
947                     if (group->defs != NULL)
948                         xmlFree(group->defs);
949                     if (group->attrs != NULL)
950                         xmlFree(group->attrs);
951                     xmlFree(group);
952                 }
953             }
954             xmlFree(partitions->groups);
955         }
956         if (partitions->triage != NULL) {
957             xmlHashFree(partitions->triage, NULL);
958         }
959         xmlFree(partitions);
960     }
961 }
962
963 /**
964  * xmlRelaxNGFreeDefine:
965  * @define:  a define structure
966  *
967  * Deallocate a RelaxNG define structure.
968  */
969 static void
970 xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define)
971 {
972     if (define == NULL)
973         return;
974
975     if ((define->type == XML_RELAXNG_VALUE) && (define->attrs != NULL)) {
976         xmlRelaxNGTypeLibraryPtr lib;
977
978         lib = (xmlRelaxNGTypeLibraryPtr) define->data;
979         if ((lib != NULL) && (lib->freef != NULL))
980             lib->freef(lib->data, (void *) define->attrs);
981     }
982     if ((define->data != NULL) && (define->type == XML_RELAXNG_INTERLEAVE))
983         xmlRelaxNGFreePartition((xmlRelaxNGPartitionPtr) define->data);
984     if ((define->data != NULL) && (define->type == XML_RELAXNG_CHOICE))
985         xmlHashFree((xmlHashTablePtr) define->data, NULL);
986     if (define->name != NULL)
987         xmlFree(define->name);
988     if (define->ns != NULL)
989         xmlFree(define->ns);
990     if (define->value != NULL)
991         xmlFree(define->value);
992     if (define->contModel != NULL)
993         xmlRegFreeRegexp(define->contModel);
994     xmlFree(define);
995 }
996
997 /**
998  * xmlRelaxNGNewStates:
999  * @ctxt:  a Relax-NG validation context
1000  * @size:  the default size for the container
1001  *
1002  * Allocate a new RelaxNG validation state container
1003  *
1004  * Returns the newly allocated structure or NULL in case or error
1005  */
1006 static xmlRelaxNGStatesPtr
1007 xmlRelaxNGNewStates(xmlRelaxNGValidCtxtPtr ctxt, int size)
1008 {
1009     xmlRelaxNGStatesPtr ret;
1010
1011     if ((ctxt != NULL) &&
1012         (ctxt->freeStates != NULL) && (ctxt->freeStatesNr > 0)) {
1013         ctxt->freeStatesNr--;
1014         ret = ctxt->freeStates[ctxt->freeStatesNr];
1015         ret->nbState = 0;
1016         return (ret);
1017     }
1018     if (size < 16)
1019         size = 16;
1020
1021     ret = (xmlRelaxNGStatesPtr) xmlMalloc(sizeof(xmlRelaxNGStates) +
1022                                           (size -
1023                                            1) *
1024                                           sizeof(xmlRelaxNGValidStatePtr));
1025     if (ret == NULL) {
1026         xmlRngVErrMemory(ctxt, "allocating states\n");
1027         return (NULL);
1028     }
1029     ret->nbState = 0;
1030     ret->maxState = size;
1031     ret->tabState = (xmlRelaxNGValidStatePtr *) xmlMalloc((size) *
1032                                                           sizeof
1033                                                           (xmlRelaxNGValidStatePtr));
1034     if (ret->tabState == NULL) {
1035         xmlRngVErrMemory(ctxt, "allocating states\n");
1036         xmlFree(ret);
1037         return (NULL);
1038     }
1039     return (ret);
1040 }
1041
1042 /**
1043  * xmlRelaxNGAddStateUniq:
1044  * @ctxt:  a Relax-NG validation context
1045  * @states:  the states container
1046  * @state:  the validation state
1047  *
1048  * Add a RelaxNG validation state to the container without checking
1049  * for unicity.
1050  *
1051  * Return 1 in case of success and 0 if this is a duplicate and -1 on error
1052  */
1053 static int
1054 xmlRelaxNGAddStatesUniq(xmlRelaxNGValidCtxtPtr ctxt,
1055                         xmlRelaxNGStatesPtr states,
1056                         xmlRelaxNGValidStatePtr state)
1057 {
1058     if (state == NULL) {
1059         return (-1);
1060     }
1061     if (states->nbState >= states->maxState) {
1062         xmlRelaxNGValidStatePtr *tmp;
1063         int size;
1064
1065         size = states->maxState * 2;
1066         tmp = (xmlRelaxNGValidStatePtr *) xmlRealloc(states->tabState,
1067                                                      (size) *
1068                                                      sizeof
1069                                                      (xmlRelaxNGValidStatePtr));
1070         if (tmp == NULL) {
1071             xmlRngVErrMemory(ctxt, "adding states\n");
1072             return (-1);
1073         }
1074         states->tabState = tmp;
1075         states->maxState = size;
1076     }
1077     states->tabState[states->nbState++] = state;
1078     return (1);
1079 }
1080
1081 /**
1082  * xmlRelaxNGAddState:
1083  * @ctxt:  a Relax-NG validation context
1084  * @states:  the states container
1085  * @state:  the validation state
1086  *
1087  * Add a RelaxNG validation state to the container
1088  *
1089  * Return 1 in case of success and 0 if this is a duplicate and -1 on error
1090  */
1091 static int
1092 xmlRelaxNGAddStates(xmlRelaxNGValidCtxtPtr ctxt,
1093                     xmlRelaxNGStatesPtr states,
1094                     xmlRelaxNGValidStatePtr state)
1095 {
1096     int i;
1097
1098     if (state == NULL || states == NULL) {
1099         return (-1);
1100     }
1101     if (states->nbState >= states->maxState) {
1102         xmlRelaxNGValidStatePtr *tmp;
1103         int size;
1104
1105         size = states->maxState * 2;
1106         tmp = (xmlRelaxNGValidStatePtr *) xmlRealloc(states->tabState,
1107                                                      (size) *
1108                                                      sizeof
1109                                                      (xmlRelaxNGValidStatePtr));
1110         if (tmp == NULL) {
1111             xmlRngVErrMemory(ctxt, "adding states\n");
1112             return (-1);
1113         }
1114         states->tabState = tmp;
1115         states->maxState = size;
1116     }
1117     for (i = 0; i < states->nbState; i++) {
1118         if (xmlRelaxNGEqualValidState(ctxt, state, states->tabState[i])) {
1119             xmlRelaxNGFreeValidState(ctxt, state);
1120             return (0);
1121         }
1122     }
1123     states->tabState[states->nbState++] = state;
1124     return (1);
1125 }
1126
1127 /**
1128  * xmlRelaxNGFreeStates:
1129  * @ctxt:  a Relax-NG validation context
1130  * @states:  teh container
1131  *
1132  * Free a RelaxNG validation state container
1133  */
1134 static void
1135 xmlRelaxNGFreeStates(xmlRelaxNGValidCtxtPtr ctxt,
1136                      xmlRelaxNGStatesPtr states)
1137 {
1138     if (states == NULL)
1139         return;
1140     if ((ctxt != NULL) && (ctxt->freeStates == NULL)) {
1141         ctxt->freeStatesMax = 40;
1142         ctxt->freeStatesNr = 0;
1143         ctxt->freeStates = (xmlRelaxNGStatesPtr *)
1144             xmlMalloc(ctxt->freeStatesMax * sizeof(xmlRelaxNGStatesPtr));
1145         if (ctxt->freeStates == NULL) {
1146             xmlRngVErrMemory(ctxt, "storing states\n");
1147         }
1148     } else if ((ctxt != NULL)
1149                && (ctxt->freeStatesNr >= ctxt->freeStatesMax)) {
1150         xmlRelaxNGStatesPtr *tmp;
1151
1152         tmp = (xmlRelaxNGStatesPtr *) xmlRealloc(ctxt->freeStates,
1153                                                  2 * ctxt->freeStatesMax *
1154                                                  sizeof
1155                                                  (xmlRelaxNGStatesPtr));
1156         if (tmp == NULL) {
1157             xmlRngVErrMemory(ctxt, "storing states\n");
1158             xmlFree(states->tabState);
1159             xmlFree(states);
1160             return;
1161         }
1162         ctxt->freeStates = tmp;
1163         ctxt->freeStatesMax *= 2;
1164     }
1165     if ((ctxt == NULL) || (ctxt->freeStates == NULL)) {
1166         xmlFree(states->tabState);
1167         xmlFree(states);
1168     } else {
1169         ctxt->freeStates[ctxt->freeStatesNr++] = states;
1170     }
1171 }
1172
1173 /**
1174  * xmlRelaxNGNewValidState:
1175  * @ctxt:  a Relax-NG validation context
1176  * @node:  the current node or NULL for the document
1177  *
1178  * Allocate a new RelaxNG validation state
1179  *
1180  * Returns the newly allocated structure or NULL in case or error
1181  */
1182 static xmlRelaxNGValidStatePtr
1183 xmlRelaxNGNewValidState(xmlRelaxNGValidCtxtPtr ctxt, xmlNodePtr node)
1184 {
1185     xmlRelaxNGValidStatePtr ret;
1186     xmlAttrPtr attr;
1187     xmlAttrPtr attrs[MAX_ATTR];
1188     int nbAttrs = 0;
1189     xmlNodePtr root = NULL;
1190
1191     if (node == NULL) {
1192         root = xmlDocGetRootElement(ctxt->doc);
1193         if (root == NULL)
1194             return (NULL);
1195     } else {
1196         attr = node->properties;
1197         while (attr != NULL) {
1198             if (nbAttrs < MAX_ATTR)
1199                 attrs[nbAttrs++] = attr;
1200             else
1201                 nbAttrs++;
1202             attr = attr->next;
1203         }
1204     }
1205     if ((ctxt->freeState != NULL) && (ctxt->freeState->nbState > 0)) {
1206         ctxt->freeState->nbState--;
1207         ret = ctxt->freeState->tabState[ctxt->freeState->nbState];
1208     } else {
1209         ret =
1210             (xmlRelaxNGValidStatePtr)
1211             xmlMalloc(sizeof(xmlRelaxNGValidState));
1212         if (ret == NULL) {
1213             xmlRngVErrMemory(ctxt, "allocating states\n");
1214             return (NULL);
1215         }
1216         memset(ret, 0, sizeof(xmlRelaxNGValidState));
1217     }
1218     ret->value = NULL;
1219     ret->endvalue = NULL;
1220     if (node == NULL) {
1221         ret->node = (xmlNodePtr) ctxt->doc;
1222         ret->seq = root;
1223     } else {
1224         ret->node = node;
1225         ret->seq = node->children;
1226     }
1227     ret->nbAttrs = 0;
1228     if (nbAttrs > 0) {
1229         if (ret->attrs == NULL) {
1230             if (nbAttrs < 4)
1231                 ret->maxAttrs = 4;
1232             else
1233                 ret->maxAttrs = nbAttrs;
1234             ret->attrs = (xmlAttrPtr *) xmlMalloc(ret->maxAttrs *
1235                                                   sizeof(xmlAttrPtr));
1236             if (ret->attrs == NULL) {
1237                 xmlRngVErrMemory(ctxt, "allocating states\n");
1238                 return (ret);
1239             }
1240         } else if (ret->maxAttrs < nbAttrs) {
1241             xmlAttrPtr *tmp;
1242
1243             tmp = (xmlAttrPtr *) xmlRealloc(ret->attrs, nbAttrs *
1244                                             sizeof(xmlAttrPtr));
1245             if (tmp == NULL) {
1246                 xmlRngVErrMemory(ctxt, "allocating states\n");
1247                 return (ret);
1248             }
1249             ret->attrs = tmp;
1250             ret->maxAttrs = nbAttrs;
1251         }
1252         ret->nbAttrs = nbAttrs;
1253         if (nbAttrs < MAX_ATTR) {
1254             memcpy(ret->attrs, attrs, sizeof(xmlAttrPtr) * nbAttrs);
1255         } else {
1256             attr = node->properties;
1257             nbAttrs = 0;
1258             while (attr != NULL) {
1259                 ret->attrs[nbAttrs++] = attr;
1260                 attr = attr->next;
1261             }
1262         }
1263     }
1264     ret->nbAttrLeft = ret->nbAttrs;
1265     return (ret);
1266 }
1267
1268 /**
1269  * xmlRelaxNGCopyValidState:
1270  * @ctxt:  a Relax-NG validation context
1271  * @state:  a validation state
1272  *
1273  * Copy the validation state
1274  *
1275  * Returns the newly allocated structure or NULL in case or error
1276  */
1277 static xmlRelaxNGValidStatePtr
1278 xmlRelaxNGCopyValidState(xmlRelaxNGValidCtxtPtr ctxt,
1279                          xmlRelaxNGValidStatePtr state)
1280 {
1281     xmlRelaxNGValidStatePtr ret;
1282     unsigned int maxAttrs;
1283     xmlAttrPtr *attrs;
1284
1285     if (state == NULL)
1286         return (NULL);
1287     if ((ctxt->freeState != NULL) && (ctxt->freeState->nbState > 0)) {
1288         ctxt->freeState->nbState--;
1289         ret = ctxt->freeState->tabState[ctxt->freeState->nbState];
1290     } else {
1291         ret =
1292             (xmlRelaxNGValidStatePtr)
1293             xmlMalloc(sizeof(xmlRelaxNGValidState));
1294         if (ret == NULL) {
1295             xmlRngVErrMemory(ctxt, "allocating states\n");
1296             return (NULL);
1297         }
1298         memset(ret, 0, sizeof(xmlRelaxNGValidState));
1299     }
1300     attrs = ret->attrs;
1301     maxAttrs = ret->maxAttrs;
1302     memcpy(ret, state, sizeof(xmlRelaxNGValidState));
1303     ret->attrs = attrs;
1304     ret->maxAttrs = maxAttrs;
1305     if (state->nbAttrs > 0) {
1306         if (ret->attrs == NULL) {
1307             ret->maxAttrs = state->maxAttrs;
1308             ret->attrs = (xmlAttrPtr *) xmlMalloc(ret->maxAttrs *
1309                                                   sizeof(xmlAttrPtr));
1310             if (ret->attrs == NULL) {
1311                 xmlRngVErrMemory(ctxt, "allocating states\n");
1312                 ret->nbAttrs = 0;
1313                 return (ret);
1314             }
1315         } else if (ret->maxAttrs < state->nbAttrs) {
1316             xmlAttrPtr *tmp;
1317
1318             tmp = (xmlAttrPtr *) xmlRealloc(ret->attrs, state->maxAttrs *
1319                                             sizeof(xmlAttrPtr));
1320             if (tmp == NULL) {
1321                 xmlRngVErrMemory(ctxt, "allocating states\n");
1322                 ret->nbAttrs = 0;
1323                 return (ret);
1324             }
1325             ret->maxAttrs = state->maxAttrs;
1326             ret->attrs = tmp;
1327         }
1328         memcpy(ret->attrs, state->attrs,
1329                state->nbAttrs * sizeof(xmlAttrPtr));
1330     }
1331     return (ret);
1332 }
1333
1334 /**
1335  * xmlRelaxNGEqualValidState:
1336  * @ctxt:  a Relax-NG validation context
1337  * @state1:  a validation state
1338  * @state2:  a validation state
1339  *
1340  * Compare the validation states for equality
1341  *
1342  * Returns 1 if equald, 0 otherwise
1343  */
1344 static int
1345 xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
1346                           xmlRelaxNGValidStatePtr state1,
1347                           xmlRelaxNGValidStatePtr state2)
1348 {
1349     int i;
1350
1351     if ((state1 == NULL) || (state2 == NULL))
1352         return (0);
1353     if (state1 == state2)
1354         return (1);
1355     if (state1->node != state2->node)
1356         return (0);
1357     if (state1->seq != state2->seq)
1358         return (0);
1359     if (state1->nbAttrLeft != state2->nbAttrLeft)
1360         return (0);
1361     if (state1->nbAttrs != state2->nbAttrs)
1362         return (0);
1363     if (state1->endvalue != state2->endvalue)
1364         return (0);
1365     if ((state1->value != state2->value) &&
1366         (!xmlStrEqual(state1->value, state2->value)))
1367         return (0);
1368     for (i = 0; i < state1->nbAttrs; i++) {
1369         if (state1->attrs[i] != state2->attrs[i])
1370             return (0);
1371     }
1372     return (1);
1373 }
1374
1375 /**
1376  * xmlRelaxNGFreeValidState:
1377  * @state:  a validation state structure
1378  *
1379  * Deallocate a RelaxNG validation state structure.
1380  */
1381 static void
1382 xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,
1383                          xmlRelaxNGValidStatePtr state)
1384 {
1385     if (state == NULL)
1386         return;
1387
1388     if ((ctxt != NULL) && (ctxt->freeState == NULL)) {
1389         ctxt->freeState = xmlRelaxNGNewStates(ctxt, 40);
1390     }
1391     if ((ctxt == NULL) || (ctxt->freeState == NULL)) {
1392         if (state->attrs != NULL)
1393             xmlFree(state->attrs);
1394         xmlFree(state);
1395     } else {
1396         xmlRelaxNGAddStatesUniq(ctxt, ctxt->freeState, state);
1397     }
1398 }
1399
1400 /************************************************************************
1401  *                                                                      *
1402  *                      Semi internal functions                         *
1403  *                                                                      *
1404  ************************************************************************/
1405
1406 /**
1407  * xmlRelaxParserSetFlag:
1408  * @ctxt: a RelaxNG parser context
1409  * @flags: a set of flags values
1410  *
1411  * Semi private function used to pass informations to a parser context
1412  * which are a combination of xmlRelaxNGParserFlag .
1413  *
1414  * Returns 0 if success and -1 in case of error
1415  */
1416 int
1417 xmlRelaxParserSetFlag(xmlRelaxNGParserCtxtPtr ctxt, int flags)
1418 {
1419     if (ctxt == NULL) return(-1);
1420     if (flags & XML_RELAXNGP_FREE_DOC) {
1421         ctxt->crng |= XML_RELAXNGP_FREE_DOC;
1422         flags -= XML_RELAXNGP_FREE_DOC;
1423     }
1424     if (flags & XML_RELAXNGP_CRNG) {
1425         ctxt->crng |= XML_RELAXNGP_CRNG;
1426         flags -= XML_RELAXNGP_CRNG;
1427     }
1428     if (flags != 0) return(-1);
1429     return(0);
1430 }
1431
1432 /************************************************************************
1433  *                                                                      *
1434  *                      Document functions                              *
1435  *                                                                      *
1436  ************************************************************************/
1437 static xmlDocPtr xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt,
1438                                       xmlDocPtr doc);
1439
1440 /**
1441  * xmlRelaxNGIncludePush:
1442  * @ctxt:  the parser context
1443  * @value:  the element doc
1444  *
1445  * Pushes a new include on top of the include stack
1446  *
1447  * Returns 0 in case of error, the index in the stack otherwise
1448  */
1449 static int
1450 xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,
1451                       xmlRelaxNGIncludePtr value)
1452 {
1453     if (ctxt->incTab == NULL) {
1454         ctxt->incMax = 4;
1455         ctxt->incNr = 0;
1456         ctxt->incTab =
1457             (xmlRelaxNGIncludePtr *) xmlMalloc(ctxt->incMax *
1458                                                sizeof(ctxt->incTab[0]));
1459         if (ctxt->incTab == NULL) {
1460             xmlRngPErrMemory(ctxt, "allocating include\n");
1461             return (0);
1462         }
1463     }
1464     if (ctxt->incNr >= ctxt->incMax) {
1465         ctxt->incMax *= 2;
1466         ctxt->incTab =
1467             (xmlRelaxNGIncludePtr *) xmlRealloc(ctxt->incTab,
1468                                                 ctxt->incMax *
1469                                                 sizeof(ctxt->incTab[0]));
1470         if (ctxt->incTab == NULL) {
1471             xmlRngPErrMemory(ctxt, "allocating include\n");
1472             return (0);
1473         }
1474     }
1475     ctxt->incTab[ctxt->incNr] = value;
1476     ctxt->inc = value;
1477     return (ctxt->incNr++);
1478 }
1479
1480 /**
1481  * xmlRelaxNGIncludePop:
1482  * @ctxt: the parser context
1483  *
1484  * Pops the top include from the include stack
1485  *
1486  * Returns the include just removed
1487  */
1488 static xmlRelaxNGIncludePtr
1489 xmlRelaxNGIncludePop(xmlRelaxNGParserCtxtPtr ctxt)
1490 {
1491     xmlRelaxNGIncludePtr ret;
1492
1493     if (ctxt->incNr <= 0)
1494         return (NULL);
1495     ctxt->incNr--;
1496     if (ctxt->incNr > 0)
1497         ctxt->inc = ctxt->incTab[ctxt->incNr - 1];
1498     else
1499         ctxt->inc = NULL;
1500     ret = ctxt->incTab[ctxt->incNr];
1501     ctxt->incTab[ctxt->incNr] = NULL;
1502     return (ret);
1503 }
1504
1505 /**
1506  * xmlRelaxNGRemoveRedefine:
1507  * @ctxt: the parser context
1508  * @URL:  the normalized URL
1509  * @target:  the included target
1510  * @name:  the define name to eliminate
1511  *
1512  * Applies the elimination algorithm of 4.7
1513  *
1514  * Returns 0 in case of error, 1 in case of success.
1515  */
1516 static int
1517 xmlRelaxNGRemoveRedefine(xmlRelaxNGParserCtxtPtr ctxt,
1518                          const xmlChar * URL ATTRIBUTE_UNUSED,
1519                          xmlNodePtr target, const xmlChar * name)
1520 {
1521     int found = 0;
1522     xmlNodePtr tmp, tmp2;
1523     xmlChar *name2;
1524
1525 #ifdef DEBUG_INCLUDE
1526     if (name == NULL)
1527         xmlGenericError(xmlGenericErrorContext,
1528                         "Elimination of <include> start from %s\n", URL);
1529     else
1530         xmlGenericError(xmlGenericErrorContext,
1531                         "Elimination of <include> define %s from %s\n",
1532                         name, URL);
1533 #endif
1534     tmp = target;
1535     while (tmp != NULL) {
1536         tmp2 = tmp->next;
1537         if ((name == NULL) && (IS_RELAXNG(tmp, "start"))) {
1538             found = 1;
1539             xmlUnlinkNode(tmp);
1540             xmlFreeNode(tmp);
1541         } else if ((name != NULL) && (IS_RELAXNG(tmp, "define"))) {
1542             name2 = xmlGetProp(tmp, BAD_CAST "name");
1543             xmlRelaxNGNormExtSpace(name2);
1544             if (name2 != NULL) {
1545                 if (xmlStrEqual(name, name2)) {
1546                     found = 1;
1547                     xmlUnlinkNode(tmp);
1548                     xmlFreeNode(tmp);
1549                 }
1550                 xmlFree(name2);
1551             }
1552         } else if (IS_RELAXNG(tmp, "include")) {
1553             xmlChar *href = NULL;
1554             xmlRelaxNGDocumentPtr inc = tmp->psvi;
1555
1556             if ((inc != NULL) && (inc->doc != NULL) &&
1557                 (inc->doc->children != NULL)) {
1558
1559                 if (xmlStrEqual
1560                     (inc->doc->children->name, BAD_CAST "grammar")) {
1561 #ifdef DEBUG_INCLUDE
1562                     href = xmlGetProp(tmp, BAD_CAST "href");
1563 #endif
1564                     if (xmlRelaxNGRemoveRedefine(ctxt, href,
1565                                                  xmlDocGetRootElement(inc->doc)->children,
1566                                                  name) == 1) {
1567                         found = 1;
1568                     }
1569 #ifdef DEBUG_INCLUDE
1570                     if (href != NULL)
1571                         xmlFree(href);
1572 #endif
1573                 }
1574             }
1575         }
1576         tmp = tmp2;
1577     }
1578     return (found);
1579 }
1580
1581 /**
1582  * xmlRelaxNGLoadInclude:
1583  * @ctxt: the parser context
1584  * @URL:  the normalized URL
1585  * @node: the include node.
1586  * @ns:  the namespace passed from the context.
1587  *
1588  * First lookup if the document is already loaded into the parser context,
1589  * check against recursion. If not found the resource is loaded and
1590  * the content is preprocessed before being returned back to the caller.
1591  *
1592  * Returns the xmlRelaxNGIncludePtr or NULL in case of error
1593  */
1594 static xmlRelaxNGIncludePtr
1595 xmlRelaxNGLoadInclude(xmlRelaxNGParserCtxtPtr ctxt, const xmlChar * URL,
1596                       xmlNodePtr node, const xmlChar * ns)
1597 {
1598     xmlRelaxNGIncludePtr ret = NULL;
1599     xmlDocPtr doc;
1600     int i;
1601     xmlNodePtr root, cur;
1602
1603 #ifdef DEBUG_INCLUDE
1604     xmlGenericError(xmlGenericErrorContext,
1605                     "xmlRelaxNGLoadInclude(%s)\n", URL);
1606 #endif
1607
1608     /*
1609      * check against recursion in the stack
1610      */
1611     for (i = 0; i < ctxt->incNr; i++) {
1612         if (xmlStrEqual(ctxt->incTab[i]->href, URL)) {
1613             xmlRngPErr(ctxt, NULL, XML_RNGP_INCLUDE_RECURSE,
1614                        "Detected an Include recursion for %s\n", URL,
1615                        NULL);
1616             return (NULL);
1617         }
1618     }
1619
1620     /*
1621      * load the document
1622      */
1623     doc = xmlReadFile((const char *) URL,NULL,0);
1624     if (doc == NULL) {
1625         xmlRngPErr(ctxt, node, XML_RNGP_PARSE_ERROR,
1626                    "xmlRelaxNG: could not load %s\n", URL, NULL);
1627         return (NULL);
1628     }
1629 #ifdef DEBUG_INCLUDE
1630     xmlGenericError(xmlGenericErrorContext, "Parsed %s Okay\n", URL);
1631 #endif
1632
1633     /*
1634      * Allocate the document structures and register it first.
1635      */
1636     ret = (xmlRelaxNGIncludePtr) xmlMalloc(sizeof(xmlRelaxNGInclude));
1637     if (ret == NULL) {
1638         xmlRngPErrMemory(ctxt, "allocating include\n");
1639         xmlFreeDoc(doc);
1640         return (NULL);
1641     }
1642     memset(ret, 0, sizeof(xmlRelaxNGInclude));
1643     ret->doc = doc;
1644     ret->href = xmlStrdup(URL);
1645     ret->next = ctxt->includes;
1646     ctxt->includes = ret;
1647
1648     /*
1649      * transmit the ns if needed
1650      */
1651     if (ns != NULL) {
1652         root = xmlDocGetRootElement(doc);
1653         if (root != NULL) {
1654             if (xmlHasProp(root, BAD_CAST "ns") == NULL) {
1655                 xmlSetProp(root, BAD_CAST "ns", ns);
1656             }
1657         }
1658     }
1659
1660     /*
1661      * push it on the stack
1662      */
1663     xmlRelaxNGIncludePush(ctxt, ret);
1664
1665     /*
1666      * Some preprocessing of the document content, this include recursing
1667      * in the include stack.
1668      */
1669 #ifdef DEBUG_INCLUDE
1670     xmlGenericError(xmlGenericErrorContext, "cleanup of %s\n", URL);
1671 #endif
1672
1673     doc = xmlRelaxNGCleanupDoc(ctxt, doc);
1674     if (doc == NULL) {
1675         ctxt->inc = NULL;
1676         return (NULL);
1677     }
1678
1679     /*
1680      * Pop up the include from the stack
1681      */
1682     xmlRelaxNGIncludePop(ctxt);
1683
1684 #ifdef DEBUG_INCLUDE
1685     xmlGenericError(xmlGenericErrorContext, "Checking of %s\n", URL);
1686 #endif
1687     /*
1688      * Check that the top element is a grammar
1689      */
1690     root = xmlDocGetRootElement(doc);
1691     if (root == NULL) {
1692         xmlRngPErr(ctxt, node, XML_RNGP_EMPTY,
1693                    "xmlRelaxNG: included document is empty %s\n", URL,
1694                    NULL);
1695         return (NULL);
1696     }
1697     if (!IS_RELAXNG(root, "grammar")) {
1698         xmlRngPErr(ctxt, node, XML_RNGP_GRAMMAR_MISSING,
1699                    "xmlRelaxNG: included document %s root is not a grammar\n",
1700                    URL, NULL);
1701         return (NULL);
1702     }
1703
1704     /*
1705      * Elimination of redefined rules in the include.
1706      */
1707     cur = node->children;
1708     while (cur != NULL) {
1709         if (IS_RELAXNG(cur, "start")) {
1710             int found = 0;
1711
1712             found =
1713                 xmlRelaxNGRemoveRedefine(ctxt, URL, root->children, NULL);
1714             if (!found) {
1715                 xmlRngPErr(ctxt, node, XML_RNGP_START_MISSING,
1716                            "xmlRelaxNG: include %s has a start but not the included grammar\n",
1717                            URL, NULL);
1718             }
1719         } else if (IS_RELAXNG(cur, "define")) {
1720             xmlChar *name;
1721
1722             name = xmlGetProp(cur, BAD_CAST "name");
1723             if (name == NULL) {
1724                 xmlRngPErr(ctxt, node, XML_RNGP_NAME_MISSING,
1725                            "xmlRelaxNG: include %s has define without name\n",
1726                            URL, NULL);
1727             } else {
1728                 int found;
1729
1730                 xmlRelaxNGNormExtSpace(name);
1731                 found = xmlRelaxNGRemoveRedefine(ctxt, URL,
1732                                                  root->children, name);
1733                 if (!found) {
1734                     xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_MISSING,
1735                                "xmlRelaxNG: include %s has a define %s but not the included grammar\n",
1736                                URL, name);
1737                 }
1738                 xmlFree(name);
1739             }
1740         }
1741         cur = cur->next;
1742     }
1743
1744
1745     return (ret);
1746 }
1747
1748 /**
1749  * xmlRelaxNGValidErrorPush:
1750  * @ctxt:  the validation context
1751  * @err:  the error code
1752  * @arg1:  the first string argument
1753  * @arg2:  the second string argument
1754  * @dup:  arg need to be duplicated
1755  *
1756  * Pushes a new error on top of the error stack
1757  *
1758  * Returns 0 in case of error, the index in the stack otherwise
1759  */
1760 static int
1761 xmlRelaxNGValidErrorPush(xmlRelaxNGValidCtxtPtr ctxt,
1762                          xmlRelaxNGValidErr err, const xmlChar * arg1,
1763                          const xmlChar * arg2, int dup)
1764 {
1765     xmlRelaxNGValidErrorPtr cur;
1766
1767 #ifdef DEBUG_ERROR
1768     xmlGenericError(xmlGenericErrorContext,
1769                     "Pushing error %d at %d on stack\n", err, ctxt->errNr);
1770 #endif
1771     if (ctxt->errTab == NULL) {
1772         ctxt->errMax = 8;
1773         ctxt->errNr = 0;
1774         ctxt->errTab =
1775             (xmlRelaxNGValidErrorPtr) xmlMalloc(ctxt->errMax *
1776                                                 sizeof
1777                                                 (xmlRelaxNGValidError));
1778         if (ctxt->errTab == NULL) {
1779             xmlRngVErrMemory(ctxt, "pushing error\n");
1780             return (0);
1781         }
1782         ctxt->err = NULL;
1783     }
1784     if (ctxt->errNr >= ctxt->errMax) {
1785         ctxt->errMax *= 2;
1786         ctxt->errTab =
1787             (xmlRelaxNGValidErrorPtr) xmlRealloc(ctxt->errTab,
1788                                                  ctxt->errMax *
1789                                                  sizeof
1790                                                  (xmlRelaxNGValidError));
1791         if (ctxt->errTab == NULL) {
1792             xmlRngVErrMemory(ctxt, "pushing error\n");
1793             return (0);
1794         }
1795         ctxt->err = &ctxt->errTab[ctxt->errNr - 1];
1796     }
1797     if ((ctxt->err != NULL) && (ctxt->state != NULL) &&
1798         (ctxt->err->node == ctxt->state->node) && (ctxt->err->err == err))
1799         return (ctxt->errNr);
1800     cur = &ctxt->errTab[ctxt->errNr];
1801     cur->err = err;
1802     if (dup) {
1803         cur->arg1 = xmlStrdup(arg1);
1804         cur->arg2 = xmlStrdup(arg2);
1805         cur->flags = ERROR_IS_DUP;
1806     } else {
1807         cur->arg1 = arg1;
1808         cur->arg2 = arg2;
1809         cur->flags = 0;
1810     }
1811     if (ctxt->state != NULL) {
1812         cur->node = ctxt->state->node;
1813         cur->seq = ctxt->state->seq;
1814     } else {
1815         cur->node = NULL;
1816         cur->seq = NULL;
1817     }
1818     ctxt->err = cur;
1819     return (ctxt->errNr++);
1820 }
1821
1822 /**
1823  * xmlRelaxNGValidErrorPop:
1824  * @ctxt: the validation context
1825  *
1826  * Pops the top error from the error stack
1827  */
1828 static void
1829 xmlRelaxNGValidErrorPop(xmlRelaxNGValidCtxtPtr ctxt)
1830 {
1831     xmlRelaxNGValidErrorPtr cur;
1832
1833     if (ctxt->errNr <= 0) {
1834         ctxt->err = NULL;
1835         return;
1836     }
1837     ctxt->errNr--;
1838     if (ctxt->errNr > 0)
1839         ctxt->err = &ctxt->errTab[ctxt->errNr - 1];
1840     else
1841         ctxt->err = NULL;
1842     cur = &ctxt->errTab[ctxt->errNr];
1843     if (cur->flags & ERROR_IS_DUP) {
1844         if (cur->arg1 != NULL)
1845             xmlFree((xmlChar *) cur->arg1);
1846         cur->arg1 = NULL;
1847         if (cur->arg2 != NULL)
1848             xmlFree((xmlChar *) cur->arg2);
1849         cur->arg2 = NULL;
1850         cur->flags = 0;
1851     }
1852 }
1853
1854 /**
1855  * xmlRelaxNGDocumentPush:
1856  * @ctxt:  the parser context
1857  * @value:  the element doc
1858  *
1859  * Pushes a new doc on top of the doc stack
1860  *
1861  * Returns 0 in case of error, the index in the stack otherwise
1862  */
1863 static int
1864 xmlRelaxNGDocumentPush(xmlRelaxNGParserCtxtPtr ctxt,
1865                        xmlRelaxNGDocumentPtr value)
1866 {
1867     if (ctxt->docTab == NULL) {
1868         ctxt->docMax = 4;
1869         ctxt->docNr = 0;
1870         ctxt->docTab =
1871             (xmlRelaxNGDocumentPtr *) xmlMalloc(ctxt->docMax *
1872                                                 sizeof(ctxt->docTab[0]));
1873         if (ctxt->docTab == NULL) {
1874             xmlRngPErrMemory(ctxt, "adding document\n");
1875             return (0);
1876         }
1877     }
1878     if (ctxt->docNr >= ctxt->docMax) {
1879         ctxt->docMax *= 2;
1880         ctxt->docTab =
1881             (xmlRelaxNGDocumentPtr *) xmlRealloc(ctxt->docTab,
1882                                                  ctxt->docMax *
1883                                                  sizeof(ctxt->docTab[0]));
1884         if (ctxt->docTab == NULL) {
1885             xmlRngPErrMemory(ctxt, "adding document\n");
1886             return (0);
1887         }
1888     }
1889     ctxt->docTab[ctxt->docNr] = value;
1890     ctxt->doc = value;
1891     return (ctxt->docNr++);
1892 }
1893
1894 /**
1895  * xmlRelaxNGDocumentPop:
1896  * @ctxt: the parser context
1897  *
1898  * Pops the top doc from the doc stack
1899  *
1900  * Returns the doc just removed
1901  */
1902 static xmlRelaxNGDocumentPtr
1903 xmlRelaxNGDocumentPop(xmlRelaxNGParserCtxtPtr ctxt)
1904 {
1905     xmlRelaxNGDocumentPtr ret;
1906
1907     if (ctxt->docNr <= 0)
1908         return (NULL);
1909     ctxt->docNr--;
1910     if (ctxt->docNr > 0)
1911         ctxt->doc = ctxt->docTab[ctxt->docNr - 1];
1912     else
1913         ctxt->doc = NULL;
1914     ret = ctxt->docTab[ctxt->docNr];
1915     ctxt->docTab[ctxt->docNr] = NULL;
1916     return (ret);
1917 }
1918
1919 /**
1920  * xmlRelaxNGLoadExternalRef:
1921  * @ctxt: the parser context
1922  * @URL:  the normalized URL
1923  * @ns:  the inherited ns if any
1924  *
1925  * First lookup if the document is already loaded into the parser context,
1926  * check against recursion. If not found the resource is loaded and
1927  * the content is preprocessed before being returned back to the caller.
1928  *
1929  * Returns the xmlRelaxNGDocumentPtr or NULL in case of error
1930  */
1931 static xmlRelaxNGDocumentPtr
1932 xmlRelaxNGLoadExternalRef(xmlRelaxNGParserCtxtPtr ctxt,
1933                           const xmlChar * URL, const xmlChar * ns)
1934 {
1935     xmlRelaxNGDocumentPtr ret = NULL;
1936     xmlDocPtr doc;
1937     xmlNodePtr root;
1938     int i;
1939
1940     /*
1941      * check against recursion in the stack
1942      */
1943     for (i = 0; i < ctxt->docNr; i++) {
1944         if (xmlStrEqual(ctxt->docTab[i]->href, URL)) {
1945             xmlRngPErr(ctxt, NULL, XML_RNGP_EXTERNALREF_RECURSE,
1946                        "Detected an externalRef recursion for %s\n", URL,
1947                        NULL);
1948             return (NULL);
1949         }
1950     }
1951
1952     /*
1953      * load the document
1954      */
1955     doc = xmlReadFile((const char *) URL,NULL,0);
1956     if (doc == NULL) {
1957         xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,
1958                    "xmlRelaxNG: could not load %s\n", URL, NULL);
1959         return (NULL);
1960     }
1961
1962     /*
1963      * Allocate the document structures and register it first.
1964      */
1965     ret = (xmlRelaxNGDocumentPtr) xmlMalloc(sizeof(xmlRelaxNGDocument));
1966     if (ret == NULL) {
1967         xmlRngPErr(ctxt, (xmlNodePtr) doc, XML_ERR_NO_MEMORY,
1968                    "xmlRelaxNG: allocate memory for doc %s\n", URL, NULL);
1969         xmlFreeDoc(doc);
1970         return (NULL);
1971     }
1972     memset(ret, 0, sizeof(xmlRelaxNGDocument));
1973     ret->doc = doc;
1974     ret->href = xmlStrdup(URL);
1975     ret->next = ctxt->documents;
1976     ret->externalRef = 1;
1977     ctxt->documents = ret;
1978
1979     /*
1980      * transmit the ns if needed
1981      */
1982     if (ns != NULL) {
1983         root = xmlDocGetRootElement(doc);
1984         if (root != NULL) {
1985             if (xmlHasProp(root, BAD_CAST "ns") == NULL) {
1986                 xmlSetProp(root, BAD_CAST "ns", ns);
1987             }
1988         }
1989     }
1990
1991     /*
1992      * push it on the stack and register it in the hash table
1993      */
1994     xmlRelaxNGDocumentPush(ctxt, ret);
1995
1996     /*
1997      * Some preprocessing of the document content
1998      */
1999     doc = xmlRelaxNGCleanupDoc(ctxt, doc);
2000     if (doc == NULL) {
2001         ctxt->doc = NULL;
2002         return (NULL);
2003     }
2004
2005     xmlRelaxNGDocumentPop(ctxt);
2006
2007     return (ret);
2008 }
2009
2010 /************************************************************************
2011  *                                                                      *
2012  *                      Error functions                                 *
2013  *                                                                      *
2014  ************************************************************************/
2015
2016 #define VALID_ERR(a) xmlRelaxNGAddValidError(ctxt, a, NULL, NULL, 0);
2017 #define VALID_ERR2(a, b) xmlRelaxNGAddValidError(ctxt, a, b, NULL, 0);
2018 #define VALID_ERR3(a, b, c) xmlRelaxNGAddValidError(ctxt, a, b, c, 0);
2019 #define VALID_ERR2P(a, b) xmlRelaxNGAddValidError(ctxt, a, b, NULL, 1);
2020 #define VALID_ERR3P(a, b, c) xmlRelaxNGAddValidError(ctxt, a, b, c, 1);
2021
2022 static const char *
2023 xmlRelaxNGDefName(xmlRelaxNGDefinePtr def)
2024 {
2025     if (def == NULL)
2026         return ("none");
2027     switch (def->type) {
2028         case XML_RELAXNG_EMPTY:
2029             return ("empty");
2030         case XML_RELAXNG_NOT_ALLOWED:
2031             return ("notAllowed");
2032         case XML_RELAXNG_EXCEPT:
2033             return ("except");
2034         case XML_RELAXNG_TEXT:
2035             return ("text");
2036         case XML_RELAXNG_ELEMENT:
2037             return ("element");
2038         case XML_RELAXNG_DATATYPE:
2039             return ("datatype");
2040         case XML_RELAXNG_VALUE:
2041             return ("value");
2042         case XML_RELAXNG_LIST:
2043             return ("list");
2044         case XML_RELAXNG_ATTRIBUTE:
2045             return ("attribute");
2046         case XML_RELAXNG_DEF:
2047             return ("def");
2048         case XML_RELAXNG_REF:
2049             return ("ref");
2050         case XML_RELAXNG_EXTERNALREF:
2051             return ("externalRef");
2052         case XML_RELAXNG_PARENTREF:
2053             return ("parentRef");
2054         case XML_RELAXNG_OPTIONAL:
2055             return ("optional");
2056         case XML_RELAXNG_ZEROORMORE:
2057             return ("zeroOrMore");
2058         case XML_RELAXNG_ONEORMORE:
2059             return ("oneOrMore");
2060         case XML_RELAXNG_CHOICE:
2061             return ("choice");
2062         case XML_RELAXNG_GROUP:
2063             return ("group");
2064         case XML_RELAXNG_INTERLEAVE:
2065             return ("interleave");
2066         case XML_RELAXNG_START:
2067             return ("start");
2068         case XML_RELAXNG_NOOP:
2069             return ("noop");
2070         case XML_RELAXNG_PARAM:
2071             return ("param");
2072     }
2073     return ("unknown");
2074 }
2075
2076 /**
2077  * xmlRelaxNGGetErrorString:
2078  * @err:  the error code
2079  * @arg1:  the first string argument
2080  * @arg2:  the second string argument
2081  *
2082  * computes a formatted error string for the given error code and args
2083  *
2084  * Returns the error string, it must be deallocated by the caller
2085  */
2086 static xmlChar *
2087 xmlRelaxNGGetErrorString(xmlRelaxNGValidErr err, const xmlChar * arg1,
2088                          const xmlChar * arg2)
2089 {
2090     char msg[1000];
2091
2092     if (arg1 == NULL)
2093         arg1 = BAD_CAST "";
2094     if (arg2 == NULL)
2095         arg2 = BAD_CAST "";
2096
2097     msg[0] = 0;
2098     switch (err) {
2099         case XML_RELAXNG_OK:
2100             return (NULL);
2101         case XML_RELAXNG_ERR_MEMORY:
2102             return (xmlCharStrdup("out of memory\n"));
2103         case XML_RELAXNG_ERR_TYPE:
2104             snprintf(msg, 1000, "failed to validate type %s\n", arg1);
2105             break;
2106         case XML_RELAXNG_ERR_TYPEVAL:
2107             snprintf(msg, 1000, "Type %s doesn't allow value '%s'\n", arg1,
2108                      arg2);
2109             break;
2110         case XML_RELAXNG_ERR_DUPID:
2111             snprintf(msg, 1000, "ID %s redefined\n", arg1);
2112             break;
2113         case XML_RELAXNG_ERR_TYPECMP:
2114             snprintf(msg, 1000, "failed to compare type %s\n", arg1);
2115             break;
2116         case XML_RELAXNG_ERR_NOSTATE:
2117             return (xmlCharStrdup("Internal error: no state\n"));
2118         case XML_RELAXNG_ERR_NODEFINE:
2119             return (xmlCharStrdup("Internal error: no define\n"));
2120         case XML_RELAXNG_ERR_INTERNAL:
2121             snprintf(msg, 1000, "Internal error: %s\n", arg1);
2122             break;
2123         case XML_RELAXNG_ERR_LISTEXTRA:
2124             snprintf(msg, 1000, "Extra data in list: %s\n", arg1);
2125             break;
2126         case XML_RELAXNG_ERR_INTERNODATA:
2127             return (xmlCharStrdup
2128                     ("Internal: interleave block has no data\n"));
2129         case XML_RELAXNG_ERR_INTERSEQ:
2130             return (xmlCharStrdup("Invalid sequence in interleave\n"));
2131         case XML_RELAXNG_ERR_INTEREXTRA:
2132             snprintf(msg, 1000, "Extra element %s in interleave\n", arg1);
2133             break;
2134         case XML_RELAXNG_ERR_ELEMNAME:
2135             snprintf(msg, 1000, "Expecting element %s, got %s\n", arg1,
2136                      arg2);
2137             break;
2138         case XML_RELAXNG_ERR_ELEMNONS:
2139             snprintf(msg, 1000, "Expecting a namespace for element %s\n",
2140                      arg1);
2141             break;
2142         case XML_RELAXNG_ERR_ELEMWRONGNS:
2143             snprintf(msg, 1000,
2144                      "Element %s has wrong namespace: expecting %s\n", arg1,
2145                      arg2);
2146             break;
2147         case XML_RELAXNG_ERR_ELEMWRONG:
2148             snprintf(msg, 1000, "Did not expect element %s there\n", arg1);
2149             break;
2150         case XML_RELAXNG_ERR_TEXTWRONG:
2151             snprintf(msg, 1000,
2152                      "Did not expect text in element %s content\n", arg1);
2153             break;
2154         case XML_RELAXNG_ERR_ELEMEXTRANS:
2155             snprintf(msg, 1000, "Expecting no namespace for element %s\n",
2156                      arg1);
2157             break;
2158         case XML_RELAXNG_ERR_ELEMNOTEMPTY:
2159             snprintf(msg, 1000, "Expecting element %s to be empty\n", arg1);
2160             break;
2161         case XML_RELAXNG_ERR_NOELEM:
2162             snprintf(msg, 1000, "Expecting an element %s, got nothing\n",
2163                      arg1);
2164             break;
2165         case XML_RELAXNG_ERR_NOTELEM:
2166             return (xmlCharStrdup("Expecting an element got text\n"));
2167         case XML_RELAXNG_ERR_ATTRVALID:
2168             snprintf(msg, 1000, "Element %s failed to validate attributes\n",
2169                      arg1);
2170             break;
2171         case XML_RELAXNG_ERR_CONTENTVALID:
2172             snprintf(msg, 1000, "Element %s failed to validate content\n",
2173                      arg1);
2174             break;
2175         case XML_RELAXNG_ERR_EXTRACONTENT:
2176             snprintf(msg, 1000, "Element %s has extra content: %s\n",
2177                      arg1, arg2);
2178             break;
2179         case XML_RELAXNG_ERR_INVALIDATTR:
2180             snprintf(msg, 1000, "Invalid attribute %s for element %s\n",
2181                      arg1, arg2);
2182             break;
2183         case XML_RELAXNG_ERR_LACKDATA:
2184             snprintf(msg, 1000, "Datatype element %s contains no data\n",
2185                      arg1);
2186             break;
2187         case XML_RELAXNG_ERR_DATAELEM:
2188             snprintf(msg, 1000, "Datatype element %s has child elements\n",
2189                      arg1);
2190             break;
2191         case XML_RELAXNG_ERR_VALELEM:
2192             snprintf(msg, 1000, "Value element %s has child elements\n",
2193                      arg1);
2194             break;
2195         case XML_RELAXNG_ERR_LISTELEM:
2196             snprintf(msg, 1000, "List element %s has child elements\n",
2197                      arg1);
2198             break;
2199         case XML_RELAXNG_ERR_DATATYPE:
2200             snprintf(msg, 1000, "Error validating datatype %s\n", arg1);
2201             break;
2202         case XML_RELAXNG_ERR_VALUE:
2203             snprintf(msg, 1000, "Error validating value %s\n", arg1);
2204             break;
2205         case XML_RELAXNG_ERR_LIST:
2206             return (xmlCharStrdup("Error validating list\n"));
2207         case XML_RELAXNG_ERR_NOGRAMMAR:
2208             return (xmlCharStrdup("No top grammar defined\n"));
2209         case XML_RELAXNG_ERR_EXTRADATA:
2210             return (xmlCharStrdup("Extra data in the document\n"));
2211         default:
2212             return (xmlCharStrdup("Unknown error !\n"));
2213     }
2214     if (msg[0] == 0) {
2215         snprintf(msg, 1000, "Unknown error code %d\n", err);
2216     }
2217     msg[1000 - 1] = 0;
2218     xmlChar *result = xmlCharStrdup(msg);
2219     return (xmlEscapeFormatString(&result));
2220 }
2221
2222 /**
2223  * xmlRelaxNGShowValidError:
2224  * @ctxt:  the validation context
2225  * @err:  the error number
2226  * @node:  the node
2227  * @child:  the node child generating the problem.
2228  * @arg1:  the first argument
2229  * @arg2:  the second argument
2230  *
2231  * Show a validation error.
2232  */
2233 static void
2234 xmlRelaxNGShowValidError(xmlRelaxNGValidCtxtPtr ctxt,
2235                          xmlRelaxNGValidErr err, xmlNodePtr node,
2236                          xmlNodePtr child, const xmlChar * arg1,
2237                          const xmlChar * arg2)
2238 {
2239     xmlChar *msg;
2240
2241     if (ctxt->flags & FLAGS_NOERROR)
2242         return;
2243
2244 #ifdef DEBUG_ERROR
2245     xmlGenericError(xmlGenericErrorContext, "Show error %d\n", err);
2246 #endif
2247     msg = xmlRelaxNGGetErrorString(err, arg1, arg2);
2248     if (msg == NULL)
2249         return;
2250
2251     if (ctxt->errNo == XML_RELAXNG_OK)
2252         ctxt->errNo = err;
2253     xmlRngVErr(ctxt, (child == NULL ? node : child), err,
2254                (const char *) msg, arg1, arg2);
2255     xmlFree(msg);
2256 }
2257
2258 /**
2259  * xmlRelaxNGPopErrors:
2260  * @ctxt:  the validation context
2261  * @level:  the error level in the stack
2262  *
2263  * pop and discard all errors until the given level is reached
2264  */
2265 static void
2266 xmlRelaxNGPopErrors(xmlRelaxNGValidCtxtPtr ctxt, int level)
2267 {
2268     int i;
2269     xmlRelaxNGValidErrorPtr err;
2270
2271 #ifdef DEBUG_ERROR
2272     xmlGenericError(xmlGenericErrorContext,
2273                     "Pop errors till level %d\n", level);
2274 #endif
2275     for (i = level; i < ctxt->errNr; i++) {
2276         err = &ctxt->errTab[i];
2277         if (err->flags & ERROR_IS_DUP) {
2278             if (err->arg1 != NULL)
2279                 xmlFree((xmlChar *) err->arg1);
2280             err->arg1 = NULL;
2281             if (err->arg2 != NULL)
2282                 xmlFree((xmlChar *) err->arg2);
2283             err->arg2 = NULL;
2284             err->flags = 0;
2285         }
2286     }
2287     ctxt->errNr = level;
2288     if (ctxt->errNr <= 0)
2289         ctxt->err = NULL;
2290 }
2291
2292 /**
2293  * xmlRelaxNGDumpValidError:
2294  * @ctxt:  the validation context
2295  *
2296  * Show all validation error over a given index.
2297  */
2298 static void
2299 xmlRelaxNGDumpValidError(xmlRelaxNGValidCtxtPtr ctxt)
2300 {
2301     int i, j, k;
2302     xmlRelaxNGValidErrorPtr err, dup;
2303
2304 #ifdef DEBUG_ERROR
2305     xmlGenericError(xmlGenericErrorContext,
2306                     "Dumping error stack %d errors\n", ctxt->errNr);
2307 #endif
2308     for (i = 0, k = 0; i < ctxt->errNr; i++) {
2309         err = &ctxt->errTab[i];
2310         if (k < MAX_ERROR) {
2311             for (j = 0; j < i; j++) {
2312                 dup = &ctxt->errTab[j];
2313                 if ((err->err == dup->err) && (err->node == dup->node) &&
2314                     (xmlStrEqual(err->arg1, dup->arg1)) &&
2315                     (xmlStrEqual(err->arg2, dup->arg2))) {
2316                     goto skip;
2317                 }
2318             }
2319             xmlRelaxNGShowValidError(ctxt, err->err, err->node, err->seq,
2320                                      err->arg1, err->arg2);
2321             k++;
2322         }
2323       skip:
2324         if (err->flags & ERROR_IS_DUP) {
2325             if (err->arg1 != NULL)
2326                 xmlFree((xmlChar *) err->arg1);
2327             err->arg1 = NULL;
2328             if (err->arg2 != NULL)
2329                 xmlFree((xmlChar *) err->arg2);
2330             err->arg2 = NULL;
2331             err->flags = 0;
2332         }
2333     }
2334     ctxt->errNr = 0;
2335 }
2336
2337 /**
2338  * xmlRelaxNGAddValidError:
2339  * @ctxt:  the validation context
2340  * @err:  the error number
2341  * @arg1:  the first argument
2342  * @arg2:  the second argument
2343  * @dup:  need to dup the args
2344  *
2345  * Register a validation error, either generating it if it's sure
2346  * or stacking it for later handling if unsure.
2347  */
2348 static void
2349 xmlRelaxNGAddValidError(xmlRelaxNGValidCtxtPtr ctxt,
2350                         xmlRelaxNGValidErr err, const xmlChar * arg1,
2351                         const xmlChar * arg2, int dup)
2352 {
2353     if (ctxt == NULL)
2354         return;
2355     if (ctxt->flags & FLAGS_NOERROR)
2356         return;
2357
2358 #ifdef DEBUG_ERROR
2359     xmlGenericError(xmlGenericErrorContext, "Adding error %d\n", err);
2360 #endif
2361     /*
2362      * generate the error directly
2363      */
2364     if (((ctxt->flags & FLAGS_IGNORABLE) == 0) ||
2365          (ctxt->flags & FLAGS_NEGATIVE)) {
2366         xmlNodePtr node, seq;
2367
2368         /*
2369          * Flush first any stacked error which might be the
2370          * real cause of the problem.
2371          */
2372         if (ctxt->errNr != 0)
2373             xmlRelaxNGDumpValidError(ctxt);
2374         if (ctxt->state != NULL) {
2375             node = ctxt->state->node;
2376             seq = ctxt->state->seq;
2377         } else {
2378             node = seq = NULL;
2379         }
2380         if ((node == NULL) && (seq == NULL)) {
2381             node = ctxt->pnode;
2382         }
2383         xmlRelaxNGShowValidError(ctxt, err, node, seq, arg1, arg2);
2384     }
2385     /*
2386      * Stack the error for later processing if needed
2387      */
2388     else {
2389         xmlRelaxNGValidErrorPush(ctxt, err, arg1, arg2, dup);
2390     }
2391 }
2392
2393
2394 /************************************************************************
2395  *                                                                      *
2396  *                      Type library hooks                              *
2397  *                                                                      *
2398  ************************************************************************/
2399 static xmlChar *xmlRelaxNGNormalize(xmlRelaxNGValidCtxtPtr ctxt,
2400                                     const xmlChar * str);
2401
2402 /**
2403  * xmlRelaxNGSchemaTypeHave:
2404  * @data:  data needed for the library
2405  * @type:  the type name
2406  *
2407  * Check if the given type is provided by
2408  * the W3C XMLSchema Datatype library.
2409  *
2410  * Returns 1 if yes, 0 if no and -1 in case of error.
2411  */
2412 static int
2413 xmlRelaxNGSchemaTypeHave(void *data ATTRIBUTE_UNUSED, const xmlChar * type)
2414 {
2415     xmlSchemaTypePtr typ;
2416
2417     if (type == NULL)
2418         return (-1);
2419     typ = xmlSchemaGetPredefinedType(type,
2420                                      BAD_CAST
2421                                      "http://www.w3.org/2001/XMLSchema");
2422     if (typ == NULL)
2423         return (0);
2424     return (1);
2425 }
2426
2427 /**
2428  * xmlRelaxNGSchemaTypeCheck:
2429  * @data:  data needed for the library
2430  * @type:  the type name
2431  * @value:  the value to check
2432  * @node:  the node
2433  *
2434  * Check if the given type and value are validated by
2435  * the W3C XMLSchema Datatype library.
2436  *
2437  * Returns 1 if yes, 0 if no and -1 in case of error.
2438  */
2439 static int
2440 xmlRelaxNGSchemaTypeCheck(void *data ATTRIBUTE_UNUSED,
2441                           const xmlChar * type,
2442                           const xmlChar * value,
2443                           void **result, xmlNodePtr node)
2444 {
2445     xmlSchemaTypePtr typ;
2446     int ret;
2447
2448     if ((type == NULL) || (value == NULL))
2449         return (-1);
2450     typ = xmlSchemaGetPredefinedType(type,
2451                                      BAD_CAST
2452                                      "http://www.w3.org/2001/XMLSchema");
2453     if (typ == NULL)
2454         return (-1);
2455     ret = xmlSchemaValPredefTypeNode(typ, value,
2456                                      (xmlSchemaValPtr *) result, node);
2457     if (ret == 2)               /* special ID error code */
2458         return (2);
2459     if (ret == 0)
2460         return (1);
2461     if (ret > 0)
2462         return (0);
2463     return (-1);
2464 }
2465
2466 /**
2467  * xmlRelaxNGSchemaFacetCheck:
2468  * @data:  data needed for the library
2469  * @type:  the type name
2470  * @facet:  the facet name
2471  * @val:  the facet value
2472  * @strval:  the string value
2473  * @value:  the value to check
2474  *
2475  * Function provided by a type library to check a value facet
2476  *
2477  * Returns 1 if yes, 0 if no and -1 in case of error.
2478  */
2479 static int
2480 xmlRelaxNGSchemaFacetCheck(void *data ATTRIBUTE_UNUSED,
2481                            const xmlChar * type, const xmlChar * facetname,
2482                            const xmlChar * val, const xmlChar * strval,
2483                            void *value)
2484 {
2485     xmlSchemaFacetPtr facet;
2486     xmlSchemaTypePtr typ;
2487     int ret;
2488
2489     if ((type == NULL) || (strval == NULL))
2490         return (-1);
2491     typ = xmlSchemaGetPredefinedType(type,
2492                                      BAD_CAST
2493                                      "http://www.w3.org/2001/XMLSchema");
2494     if (typ == NULL)
2495         return (-1);
2496
2497     facet = xmlSchemaNewFacet();
2498     if (facet == NULL)
2499         return (-1);
2500
2501     if (xmlStrEqual(facetname, BAD_CAST "minInclusive")) {
2502         facet->type = XML_SCHEMA_FACET_MININCLUSIVE;
2503     } else if (xmlStrEqual(facetname, BAD_CAST "minExclusive")) {
2504         facet->type = XML_SCHEMA_FACET_MINEXCLUSIVE;
2505     } else if (xmlStrEqual(facetname, BAD_CAST "maxInclusive")) {
2506         facet->type = XML_SCHEMA_FACET_MAXINCLUSIVE;
2507     } else if (xmlStrEqual(facetname, BAD_CAST "maxExclusive")) {
2508         facet->type = XML_SCHEMA_FACET_MAXEXCLUSIVE;
2509     } else if (xmlStrEqual(facetname, BAD_CAST "totalDigits")) {
2510         facet->type = XML_SCHEMA_FACET_TOTALDIGITS;
2511     } else if (xmlStrEqual(facetname, BAD_CAST "fractionDigits")) {
2512         facet->type = XML_SCHEMA_FACET_FRACTIONDIGITS;
2513     } else if (xmlStrEqual(facetname, BAD_CAST "pattern")) {
2514         facet->type = XML_SCHEMA_FACET_PATTERN;
2515     } else if (xmlStrEqual(facetname, BAD_CAST "enumeration")) {
2516         facet->type = XML_SCHEMA_FACET_ENUMERATION;
2517     } else if (xmlStrEqual(facetname, BAD_CAST "whiteSpace")) {
2518         facet->type = XML_SCHEMA_FACET_WHITESPACE;
2519     } else if (xmlStrEqual(facetname, BAD_CAST "length")) {
2520         facet->type = XML_SCHEMA_FACET_LENGTH;
2521     } else if (xmlStrEqual(facetname, BAD_CAST "maxLength")) {
2522         facet->type = XML_SCHEMA_FACET_MAXLENGTH;
2523     } else if (xmlStrEqual(facetname, BAD_CAST "minLength")) {
2524         facet->type = XML_SCHEMA_FACET_MINLENGTH;
2525     } else {
2526         xmlSchemaFreeFacet(facet);
2527         return (-1);
2528     }
2529     facet->value = val;
2530     ret = xmlSchemaCheckFacet(facet, typ, NULL, type);
2531     if (ret != 0) {
2532         xmlSchemaFreeFacet(facet);
2533         return (-1);
2534     }
2535     ret = xmlSchemaValidateFacet(typ, facet, strval, value);
2536     xmlSchemaFreeFacet(facet);
2537     if (ret != 0)
2538         return (-1);
2539     return (0);
2540 }
2541
2542 /**
2543  * xmlRelaxNGSchemaFreeValue:
2544  * @data:  data needed for the library
2545  * @value:  the value to free
2546  *
2547  * Function provided by a type library to free a Schemas value
2548  *
2549  * Returns 1 if yes, 0 if no and -1 in case of error.
2550  */
2551 static void
2552 xmlRelaxNGSchemaFreeValue(void *data ATTRIBUTE_UNUSED, void *value)
2553 {
2554     xmlSchemaFreeValue(value);
2555 }
2556
2557 /**
2558  * xmlRelaxNGSchemaTypeCompare:
2559  * @data:  data needed for the library
2560  * @type:  the type name
2561  * @value1:  the first value
2562  * @value2:  the second value
2563  *
2564  * Compare two values for equality accordingly a type from the W3C XMLSchema
2565  * Datatype library.
2566  *
2567  * Returns 1 if equal, 0 if no and -1 in case of error.
2568  */
2569 static int
2570 xmlRelaxNGSchemaTypeCompare(void *data ATTRIBUTE_UNUSED,
2571                             const xmlChar * type,
2572                             const xmlChar * value1,
2573                             xmlNodePtr ctxt1,
2574                             void *comp1,
2575                             const xmlChar * value2, xmlNodePtr ctxt2)
2576 {
2577     int ret;
2578     xmlSchemaTypePtr typ;
2579     xmlSchemaValPtr res1 = NULL, res2 = NULL;
2580
2581     if ((type == NULL) || (value1 == NULL) || (value2 == NULL))
2582         return (-1);
2583     typ = xmlSchemaGetPredefinedType(type,
2584                                      BAD_CAST
2585                                      "http://www.w3.org/2001/XMLSchema");
2586     if (typ == NULL)
2587         return (-1);
2588     if (comp1 == NULL) {
2589         ret = xmlSchemaValPredefTypeNode(typ, value1, &res1, ctxt1);
2590         if (ret != 0)
2591             return (-1);
2592         if (res1 == NULL)
2593             return (-1);
2594     } else {
2595         res1 = (xmlSchemaValPtr) comp1;
2596     }
2597     ret = xmlSchemaValPredefTypeNode(typ, value2, &res2, ctxt2);
2598     if (ret != 0) {
2599         if (res1 != (xmlSchemaValPtr) comp1)
2600             xmlSchemaFreeValue(res1);
2601         return (-1);
2602     }
2603     ret = xmlSchemaCompareValues(res1, res2);
2604     if (res1 != (xmlSchemaValPtr) comp1)
2605         xmlSchemaFreeValue(res1);
2606     xmlSchemaFreeValue(res2);
2607     if (ret == -2)
2608         return (-1);
2609     if (ret == 0)
2610         return (1);
2611     return (0);
2612 }
2613
2614 /**
2615  * xmlRelaxNGDefaultTypeHave:
2616  * @data:  data needed for the library
2617  * @type:  the type name
2618  *
2619  * Check if the given type is provided by
2620  * the default datatype library.
2621  *
2622  * Returns 1 if yes, 0 if no and -1 in case of error.
2623  */
2624 static int
2625 xmlRelaxNGDefaultTypeHave(void *data ATTRIBUTE_UNUSED,
2626                           const xmlChar * type)
2627 {
2628     if (type == NULL)
2629         return (-1);
2630     if (xmlStrEqual(type, BAD_CAST "string"))
2631         return (1);
2632     if (xmlStrEqual(type, BAD_CAST "token"))
2633         return (1);
2634     return (0);
2635 }
2636
2637 /**
2638  * xmlRelaxNGDefaultTypeCheck:
2639  * @data:  data needed for the library
2640  * @type:  the type name
2641  * @value:  the value to check
2642  * @node:  the node
2643  *
2644  * Check if the given type and value are validated by
2645  * the default datatype library.
2646  *
2647  * Returns 1 if yes, 0 if no and -1 in case of error.
2648  */
2649 static int
2650 xmlRelaxNGDefaultTypeCheck(void *data ATTRIBUTE_UNUSED,
2651                            const xmlChar * type ATTRIBUTE_UNUSED,
2652                            const xmlChar * value ATTRIBUTE_UNUSED,
2653                            void **result ATTRIBUTE_UNUSED,
2654                            xmlNodePtr node ATTRIBUTE_UNUSED)
2655 {
2656     if (value == NULL)
2657         return (-1);
2658     if (xmlStrEqual(type, BAD_CAST "string"))
2659         return (1);
2660     if (xmlStrEqual(type, BAD_CAST "token")) {
2661         return (1);
2662     }
2663
2664     return (0);
2665 }
2666
2667 /**
2668  * xmlRelaxNGDefaultTypeCompare:
2669  * @data:  data needed for the library
2670  * @type:  the type name
2671  * @value1:  the first value
2672  * @value2:  the second value
2673  *
2674  * Compare two values accordingly a type from the default
2675  * datatype library.
2676  *
2677  * Returns 1 if yes, 0 if no and -1 in case of error.
2678  */
2679 static int
2680 xmlRelaxNGDefaultTypeCompare(void *data ATTRIBUTE_UNUSED,
2681                              const xmlChar * type,
2682                              const xmlChar * value1,
2683                              xmlNodePtr ctxt1 ATTRIBUTE_UNUSED,
2684                              void *comp1 ATTRIBUTE_UNUSED,
2685                              const xmlChar * value2,
2686                              xmlNodePtr ctxt2 ATTRIBUTE_UNUSED)
2687 {
2688     int ret = -1;
2689
2690     if (xmlStrEqual(type, BAD_CAST "string")) {
2691         ret = xmlStrEqual(value1, value2);
2692     } else if (xmlStrEqual(type, BAD_CAST "token")) {
2693         if (!xmlStrEqual(value1, value2)) {
2694             xmlChar *nval, *nvalue;
2695
2696             /*
2697              * TODO: trivial optimizations are possible by
2698              * computing at compile-time
2699              */
2700             nval = xmlRelaxNGNormalize(NULL, value1);
2701             nvalue = xmlRelaxNGNormalize(NULL, value2);
2702
2703             if ((nval == NULL) || (nvalue == NULL))
2704                 ret = -1;
2705             else if (xmlStrEqual(nval, nvalue))
2706                 ret = 1;
2707             else
2708                 ret = 0;
2709             if (nval != NULL)
2710                 xmlFree(nval);
2711             if (nvalue != NULL)
2712                 xmlFree(nvalue);
2713         } else
2714             ret = 1;
2715     }
2716     return (ret);
2717 }
2718
2719 static int xmlRelaxNGTypeInitialized = 0;
2720 static xmlHashTablePtr xmlRelaxNGRegisteredTypes = NULL;
2721
2722 /**
2723  * xmlRelaxNGFreeTypeLibrary:
2724  * @lib:  the type library structure
2725  * @namespace:  the URI bound to the library
2726  *
2727  * Free the structure associated to the type library
2728  */
2729 static void
2730 xmlRelaxNGFreeTypeLibrary(xmlRelaxNGTypeLibraryPtr lib,
2731                           const xmlChar * namespace ATTRIBUTE_UNUSED)
2732 {
2733     if (lib == NULL)
2734         return;
2735     if (lib->namespace != NULL)
2736         xmlFree((xmlChar *) lib->namespace);
2737     xmlFree(lib);
2738 }
2739
2740 /**
2741  * xmlRelaxNGRegisterTypeLibrary:
2742  * @namespace:  the URI bound to the library
2743  * @data:  data associated to the library
2744  * @have:  the provide function
2745  * @check:  the checking function
2746  * @comp:  the comparison function
2747  *
2748  * Register a new type library
2749  *
2750  * Returns 0 in case of success and -1 in case of error.
2751  */
2752 static int
2753 xmlRelaxNGRegisterTypeLibrary(const xmlChar * namespace, void *data,
2754                               xmlRelaxNGTypeHave have,
2755                               xmlRelaxNGTypeCheck check,
2756                               xmlRelaxNGTypeCompare comp,
2757                               xmlRelaxNGFacetCheck facet,
2758                               xmlRelaxNGTypeFree freef)
2759 {
2760     xmlRelaxNGTypeLibraryPtr lib;
2761     int ret;
2762
2763     if ((xmlRelaxNGRegisteredTypes == NULL) || (namespace == NULL) ||
2764         (check == NULL) || (comp == NULL))
2765         return (-1);
2766     if (xmlHashLookup(xmlRelaxNGRegisteredTypes, namespace) != NULL) {
2767         xmlGenericError(xmlGenericErrorContext,
2768                         "Relax-NG types library '%s' already registered\n",
2769                         namespace);
2770         return (-1);
2771     }
2772     lib =
2773         (xmlRelaxNGTypeLibraryPtr)
2774         xmlMalloc(sizeof(xmlRelaxNGTypeLibrary));
2775     if (lib == NULL) {
2776         xmlRngVErrMemory(NULL, "adding types library\n");
2777         return (-1);
2778     }
2779     memset(lib, 0, sizeof(xmlRelaxNGTypeLibrary));
2780     lib->namespace = xmlStrdup(namespace);
2781     lib->data = data;
2782     lib->have = have;
2783     lib->comp = comp;
2784     lib->check = check;
2785     lib->facet = facet;
2786     lib->freef = freef;
2787     ret = xmlHashAddEntry(xmlRelaxNGRegisteredTypes, namespace, lib);
2788     if (ret < 0) {
2789         xmlGenericError(xmlGenericErrorContext,
2790                         "Relax-NG types library failed to register '%s'\n",
2791                         namespace);
2792         xmlRelaxNGFreeTypeLibrary(lib, namespace);
2793         return (-1);
2794     }
2795     return (0);
2796 }
2797
2798 /**
2799  * xmlRelaxNGInitTypes:
2800  *
2801  * Initilize the default type libraries.
2802  *
2803  * Returns 0 in case of success and -1 in case of error.
2804  */
2805 int
2806 xmlRelaxNGInitTypes(void)
2807 {
2808     if (xmlRelaxNGTypeInitialized != 0)
2809         return (0);
2810     xmlRelaxNGRegisteredTypes = xmlHashCreate(10);
2811     if (xmlRelaxNGRegisteredTypes == NULL) {
2812         xmlGenericError(xmlGenericErrorContext,
2813                         "Failed to allocate sh table for Relax-NG types\n");
2814         return (-1);
2815     }
2816     xmlRelaxNGRegisterTypeLibrary(BAD_CAST
2817                                   "http://www.w3.org/2001/XMLSchema-datatypes",
2818                                   NULL, xmlRelaxNGSchemaTypeHave,
2819                                   xmlRelaxNGSchemaTypeCheck,
2820                                   xmlRelaxNGSchemaTypeCompare,
2821                                   xmlRelaxNGSchemaFacetCheck,
2822                                   xmlRelaxNGSchemaFreeValue);
2823     xmlRelaxNGRegisterTypeLibrary(xmlRelaxNGNs, NULL,
2824                                   xmlRelaxNGDefaultTypeHave,
2825                                   xmlRelaxNGDefaultTypeCheck,
2826                                   xmlRelaxNGDefaultTypeCompare, NULL,
2827                                   NULL);
2828     xmlRelaxNGTypeInitialized = 1;
2829     return (0);
2830 }
2831
2832 /**
2833  * xmlRelaxNGCleanupTypes:
2834  *
2835  * Cleanup the default Schemas type library associated to RelaxNG
2836  */
2837 void
2838 xmlRelaxNGCleanupTypes(void)
2839 {
2840     xmlSchemaCleanupTypes();
2841     if (xmlRelaxNGTypeInitialized == 0)
2842         return;
2843     xmlHashFree(xmlRelaxNGRegisteredTypes, (xmlHashDeallocator)
2844                 xmlRelaxNGFreeTypeLibrary);
2845     xmlRelaxNGTypeInitialized = 0;
2846 }
2847
2848 /************************************************************************
2849  *                                                                      *
2850  *              Compiling element content into regexp                   *
2851  *                                                                      *
2852  * Sometime the element content can be compiled into a pure regexp,     *
2853  * This allows a faster execution and streamability at that level       *
2854  *                                                                      *
2855  ************************************************************************/
2856
2857 /* from automata.c but not exported */
2858 void xmlAutomataSetFlags(xmlAutomataPtr am, int flags);
2859
2860
2861 static int xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt,
2862                                 xmlRelaxNGDefinePtr def);
2863
2864 /**
2865  * xmlRelaxNGIsCompileable:
2866  * @define:  the definition to check
2867  *
2868  * Check if a definition is nullable.
2869  *
2870  * Returns 1 if yes, 0 if no and -1 in case of error
2871  */
2872 static int
2873 xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
2874 {
2875     int ret = -1;
2876
2877     if (def == NULL) {
2878         return (-1);
2879     }
2880     if ((def->type != XML_RELAXNG_ELEMENT) &&
2881         (def->dflags & IS_COMPILABLE))
2882         return (1);
2883     if ((def->type != XML_RELAXNG_ELEMENT) &&
2884         (def->dflags & IS_NOT_COMPILABLE))
2885         return (0);
2886     switch (def->type) {
2887         case XML_RELAXNG_NOOP:
2888             ret = xmlRelaxNGIsCompileable(def->content);
2889             break;
2890         case XML_RELAXNG_TEXT:
2891         case XML_RELAXNG_EMPTY:
2892             ret = 1;
2893             break;
2894         case XML_RELAXNG_ELEMENT:
2895             /*
2896              * Check if the element content is compileable
2897              */
2898             if (((def->dflags & IS_NOT_COMPILABLE) == 0) &&
2899                 ((def->dflags & IS_COMPILABLE) == 0)) {
2900                 xmlRelaxNGDefinePtr list;
2901
2902                 list = def->content;
2903                 while (list != NULL) {
2904                     ret = xmlRelaxNGIsCompileable(list);
2905                     if (ret != 1)
2906                         break;
2907                     list = list->next;
2908                 }
2909                 /*
2910                  * Because the routine is recursive, we must guard against
2911                  * discovering both COMPILABLE and NOT_COMPILABLE
2912                  */
2913                 if (ret == 0) {
2914                     def->dflags &= ~IS_COMPILABLE;
2915                     def->dflags |= IS_NOT_COMPILABLE;
2916                 }
2917                 if ((ret == 1) && !(def->dflags &= IS_NOT_COMPILABLE))
2918                     def->dflags |= IS_COMPILABLE;
2919 #ifdef DEBUG_COMPILE
2920                 if (ret == 1) {
2921                     xmlGenericError(xmlGenericErrorContext,
2922                                     "element content for %s is compilable\n",
2923                                     def->name);
2924                 } else if (ret == 0) {
2925                     xmlGenericError(xmlGenericErrorContext,
2926                                     "element content for %s is not compilable\n",
2927                                     def->name);
2928                 } else {
2929                     xmlGenericError(xmlGenericErrorContext,
2930                                     "Problem in RelaxNGIsCompileable for element %s\n",
2931                                     def->name);
2932                 }
2933 #endif
2934             }
2935             /*
2936              * All elements return a compileable status unless they
2937              * are generic like anyName
2938              */
2939             if ((def->nameClass != NULL) || (def->name == NULL))
2940                 ret = 0;
2941             else
2942                 ret = 1;
2943             return (ret);
2944         case XML_RELAXNG_REF:
2945         case XML_RELAXNG_EXTERNALREF:
2946         case XML_RELAXNG_PARENTREF:
2947             if (def->depth == -20) {
2948                 return (1);
2949             } else {
2950                 xmlRelaxNGDefinePtr list;
2951
2952                 def->depth = -20;
2953                 list = def->content;
2954                 while (list != NULL) {
2955                     ret = xmlRelaxNGIsCompileable(list);
2956                     if (ret != 1)
2957                         break;
2958                     list = list->next;
2959                 }
2960             }
2961             break;
2962         case XML_RELAXNG_START:
2963         case XML_RELAXNG_OPTIONAL:
2964         case XML_RELAXNG_ZEROORMORE:
2965         case XML_RELAXNG_ONEORMORE:
2966         case XML_RELAXNG_CHOICE:
2967         case XML_RELAXNG_GROUP:
2968         case XML_RELAXNG_DEF:{
2969                 xmlRelaxNGDefinePtr list;
2970
2971                 list = def->content;
2972                 while (list != NULL) {
2973                     ret = xmlRelaxNGIsCompileable(list);
2974                     if (ret != 1)
2975                         break;
2976                     list = list->next;
2977                 }
2978                 break;
2979             }
2980         case XML_RELAXNG_EXCEPT:
2981         case XML_RELAXNG_ATTRIBUTE:
2982         case XML_RELAXNG_INTERLEAVE:
2983         case XML_RELAXNG_DATATYPE:
2984         case XML_RELAXNG_LIST:
2985         case XML_RELAXNG_PARAM:
2986         case XML_RELAXNG_VALUE:
2987         case XML_RELAXNG_NOT_ALLOWED:
2988             ret = 0;
2989             break;
2990     }
2991     if (ret == 0)
2992         def->dflags |= IS_NOT_COMPILABLE;
2993     if (ret == 1)
2994         def->dflags |= IS_COMPILABLE;
2995 #ifdef DEBUG_COMPILE
2996     if (ret == 1) {
2997         xmlGenericError(xmlGenericErrorContext,
2998                         "RelaxNGIsCompileable %s : true\n",
2999                         xmlRelaxNGDefName(def));
3000     } else if (ret == 0) {
3001         xmlGenericError(xmlGenericErrorContext,
3002                         "RelaxNGIsCompileable %s : false\n",
3003                         xmlRelaxNGDefName(def));
3004     } else {
3005         xmlGenericError(xmlGenericErrorContext,
3006                         "Problem in RelaxNGIsCompileable %s\n",
3007                         xmlRelaxNGDefName(def));
3008     }
3009 #endif
3010     return (ret);
3011 }
3012
3013 /**
3014  * xmlRelaxNGCompile:
3015  * ctxt:  the RelaxNG parser context
3016  * @define:  the definition tree to compile
3017  *
3018  * Compile the set of definitions, it works recursively, till the
3019  * element boundaries, where it tries to compile the content if possible
3020  *
3021  * Returns 0 if success and -1 in case of error
3022  */
3023 static int
3024 xmlRelaxNGCompile(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGDefinePtr def)
3025 {
3026     int ret = 0;
3027     xmlRelaxNGDefinePtr list;
3028
3029     if ((ctxt == NULL) || (def == NULL))
3030         return (-1);
3031
3032     switch (def->type) {
3033         case XML_RELAXNG_START:
3034             if ((xmlRelaxNGIsCompileable(def) == 1) && (def->depth != -25)) {
3035                 xmlAutomataPtr oldam = ctxt->am;
3036                 xmlAutomataStatePtr oldstate = ctxt->state;
3037
3038                 def->depth = -25;
3039
3040                 list = def->content;
3041                 ctxt->am = xmlNewAutomata();
3042                 if (ctxt->am == NULL)
3043                     return (-1);
3044
3045                 /*
3046                  * assume identical strings but not same pointer are different
3047                  * atoms, needed for non-determinism detection
3048                  * That way if 2 elements with the same name are in a choice
3049                  * branch the automata is found non-deterministic and
3050                  * we fallback to the normal validation which does the right
3051                  * thing of exploring both choices.
3052                  */
3053                 xmlAutomataSetFlags(ctxt->am, 1);
3054
3055                 ctxt->state = xmlAutomataGetInitState(ctxt->am);
3056                 while (list != NULL) {
3057                     xmlRelaxNGCompile(ctxt, list);
3058                     list = list->next;
3059                 }
3060                 xmlAutomataSetFinalState(ctxt->am, ctxt->state);
3061                 if (xmlAutomataIsDeterminist(ctxt->am))
3062                     def->contModel = xmlAutomataCompile(ctxt->am);
3063
3064                 xmlFreeAutomata(ctxt->am);
3065                 ctxt->state = oldstate;
3066                 ctxt->am = oldam;
3067             }
3068             break;
3069         case XML_RELAXNG_ELEMENT:
3070             if ((ctxt->am != NULL) && (def->name != NULL)) {
3071                 ctxt->state = xmlAutomataNewTransition2(ctxt->am,
3072                                                         ctxt->state, NULL,
3073                                                         def->name, def->ns,
3074                                                         def);
3075             }
3076             if ((def->dflags & IS_COMPILABLE) && (def->depth != -25)) {
3077                 xmlAutomataPtr oldam = ctxt->am;
3078                 xmlAutomataStatePtr oldstate = ctxt->state;
3079
3080                 def->depth = -25;
3081
3082                 list = def->content;
3083                 ctxt->am = xmlNewAutomata();
3084                 if (ctxt->am == NULL)
3085                     return (-1);
3086                 xmlAutomataSetFlags(ctxt->am, 1);
3087                 ctxt->state = xmlAutomataGetInitState(ctxt->am);
3088                 while (list != NULL) {
3089                     xmlRelaxNGCompile(ctxt, list);
3090                     list = list->next;
3091                 }
3092                 xmlAutomataSetFinalState(ctxt->am, ctxt->state);
3093                 def->contModel = xmlAutomataCompile(ctxt->am);
3094                 if (!xmlRegexpIsDeterminist(def->contModel)) {
3095 #ifdef DEBUG_COMPILE
3096                     xmlGenericError(xmlGenericErrorContext,
3097                         "Content model not determinist %s\n",
3098                                     def->name);
3099 #endif
3100                     /*
3101                      * we can only use the automata if it is determinist
3102                      */
3103                     xmlRegFreeRegexp(def->contModel);
3104                     def->contModel = NULL;
3105                 }
3106                 xmlFreeAutomata(ctxt->am);
3107                 ctxt->state = oldstate;
3108                 ctxt->am = oldam;
3109             } else {
3110                 xmlAutomataPtr oldam = ctxt->am;
3111
3112                 /*
3113                  * we can't build the content model for this element content
3114                  * but it still might be possible to build it for some of its
3115                  * children, recurse.
3116                  */
3117                 ret = xmlRelaxNGTryCompile(ctxt, def);
3118                 ctxt->am = oldam;
3119             }
3120             break;
3121         case XML_RELAXNG_NOOP:
3122             ret = xmlRelaxNGCompile(ctxt, def->content);
3123             break;
3124         case XML_RELAXNG_OPTIONAL:{
3125                 xmlAutomataStatePtr oldstate = ctxt->state;
3126
3127                 list = def->content;
3128                 while (list != NULL) {
3129                     xmlRelaxNGCompile(ctxt, list);
3130                     list = list->next;
3131                 }
3132                 xmlAutomataNewEpsilon(ctxt->am, oldstate, ctxt->state);
3133                 break;
3134             }
3135         case XML_RELAXNG_ZEROORMORE:{
3136                 xmlAutomataStatePtr oldstate;
3137
3138                 ctxt->state =
3139                     xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL);
3140                 oldstate = ctxt->state;
3141                 list = def->content;
3142                 while (list != NULL) {
3143                     xmlRelaxNGCompile(ctxt, list);
3144                     list = list->next;
3145                 }
3146                 xmlAutomataNewEpsilon(ctxt->am, ctxt->state, oldstate);
3147                 ctxt->state =
3148                     xmlAutomataNewEpsilon(ctxt->am, oldstate, NULL);
3149                 break;
3150             }
3151         case XML_RELAXNG_ONEORMORE:{
3152                 xmlAutomataStatePtr oldstate;
3153
3154                 list = def->content;
3155                 while (list != NULL) {
3156                     xmlRelaxNGCompile(ctxt, list);
3157                     list = list->next;
3158                 }
3159                 oldstate = ctxt->state;
3160                 list = def->content;
3161                 while (list != NULL) {
3162                     xmlRelaxNGCompile(ctxt, list);
3163                     list = list->next;
3164                 }
3165                 xmlAutomataNewEpsilon(ctxt->am, ctxt->state, oldstate);
3166                 ctxt->state =
3167                     xmlAutomataNewEpsilon(ctxt->am, oldstate, NULL);
3168                 break;
3169             }
3170         case XML_RELAXNG_CHOICE:{
3171                 xmlAutomataStatePtr target = NULL;
3172                 xmlAutomataStatePtr oldstate = ctxt->state;
3173
3174                 list = def->content;
3175                 while (list != NULL) {
3176                     ctxt->state = oldstate;
3177                     ret = xmlRelaxNGCompile(ctxt, list);
3178                     if (ret != 0)
3179                         break;
3180                     if (target == NULL)
3181                         target = ctxt->state;
3182                     else {
3183                         xmlAutomataNewEpsilon(ctxt->am, ctxt->state,
3184                                               target);
3185                     }
3186                     list = list->next;
3187                 }
3188                 ctxt->state = target;
3189
3190                 break;
3191             }
3192         case XML_RELAXNG_REF:
3193         case XML_RELAXNG_EXTERNALREF:
3194         case XML_RELAXNG_PARENTREF:
3195         case XML_RELAXNG_GROUP:
3196         case XML_RELAXNG_DEF:
3197             list = def->content;
3198             while (list != NULL) {
3199                 ret = xmlRelaxNGCompile(ctxt, list);
3200                 if (ret != 0)
3201                     break;
3202                 list = list->next;
3203             }
3204             break;
3205         case XML_RELAXNG_TEXT:{
3206                 xmlAutomataStatePtr oldstate;
3207
3208                 ctxt->state =
3209                     xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL);
3210                 oldstate = ctxt->state;
3211                 xmlRelaxNGCompile(ctxt, def->content);
3212                 xmlAutomataNewTransition(ctxt->am, ctxt->state,
3213                                          ctxt->state, BAD_CAST "#text",
3214                                          NULL);
3215                 ctxt->state =
3216                     xmlAutomataNewEpsilon(ctxt->am, oldstate, NULL);
3217                 break;
3218             }
3219         case XML_RELAXNG_EMPTY:
3220             ctxt->state =
3221                 xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL);
3222             break;
3223         case XML_RELAXNG_EXCEPT:
3224         case XML_RELAXNG_ATTRIBUTE:
3225         case XML_RELAXNG_INTERLEAVE:
3226         case XML_RELAXNG_NOT_ALLOWED:
3227         case XML_RELAXNG_DATATYPE:
3228         case XML_RELAXNG_LIST:
3229         case XML_RELAXNG_PARAM:
3230         case XML_RELAXNG_VALUE:
3231             /* This should not happen and generate an internal error */
3232             fprintf(stderr, "RNG internal error trying to compile %s\n",
3233                     xmlRelaxNGDefName(def));
3234             break;
3235     }
3236     return (ret);
3237 }
3238
3239 /**
3240  * xmlRelaxNGTryCompile:
3241  * ctxt:  the RelaxNG parser context
3242  * @define:  the definition tree to compile
3243  *
3244  * Try to compile the set of definitions, it works recursively,
3245  * possibly ignoring parts which cannot be compiled.
3246  *
3247  * Returns 0 if success and -1 in case of error
3248  */
3249 static int
3250 xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGDefinePtr def)
3251 {
3252     int ret = 0;
3253     xmlRelaxNGDefinePtr list;
3254
3255     if ((ctxt == NULL) || (def == NULL))
3256         return (-1);
3257
3258     if ((def->type == XML_RELAXNG_START) ||
3259         (def->type == XML_RELAXNG_ELEMENT)) {
3260         ret = xmlRelaxNGIsCompileable(def);
3261         if ((def->dflags & IS_COMPILABLE) && (def->depth != -25)) {
3262             ctxt->am = NULL;
3263             ret = xmlRelaxNGCompile(ctxt, def);
3264 #ifdef DEBUG_PROGRESSIVE
3265             if (ret == 0) {
3266                 if (def->type == XML_RELAXNG_START)
3267                     xmlGenericError(xmlGenericErrorContext,
3268                                     "compiled the start\n");
3269                 else
3270                     xmlGenericError(xmlGenericErrorContext,
3271                                     "compiled element %s\n", def->name);
3272             } else {
3273                 if (def->type == XML_RELAXNG_START)
3274                     xmlGenericError(xmlGenericErrorContext,
3275                                     "failed to compile the start\n");
3276                 else
3277                     xmlGenericError(xmlGenericErrorContext,
3278                                     "failed to compile element %s\n",
3279                                     def->name);
3280             }
3281 #endif
3282             return (ret);
3283         }
3284     }
3285     switch (def->type) {
3286         case XML_RELAXNG_NOOP:
3287             ret = xmlRelaxNGTryCompile(ctxt, def->content);
3288             break;
3289         case XML_RELAXNG_TEXT:
3290         case XML_RELAXNG_DATATYPE:
3291         case XML_RELAXNG_LIST:
3292         case XML_RELAXNG_PARAM:
3293         case XML_RELAXNG_VALUE:
3294         case XML_RELAXNG_EMPTY:
3295         case XML_RELAXNG_ELEMENT:
3296             ret = 0;
3297             break;
3298         case XML_RELAXNG_OPTIONAL:
3299         case XML_RELAXNG_ZEROORMORE:
3300         case XML_RELAXNG_ONEORMORE:
3301         case XML_RELAXNG_CHOICE:
3302         case XML_RELAXNG_GROUP:
3303         case XML_RELAXNG_DEF:
3304         case XML_RELAXNG_START:
3305         case XML_RELAXNG_REF:
3306         case XML_RELAXNG_EXTERNALREF:
3307         case XML_RELAXNG_PARENTREF:
3308             list = def->content;
3309             while (list != NULL) {
3310                 ret = xmlRelaxNGTryCompile(ctxt, list);
3311                 if (ret != 0)
3312                     break;
3313                 list = list->next;
3314             }
3315             break;
3316         case XML_RELAXNG_EXCEPT:
3317         case XML_RELAXNG_ATTRIBUTE:
3318         case XML_RELAXNG_INTERLEAVE:
3319         case XML_RELAXNG_NOT_ALLOWED:
3320             ret = 0;
3321             break;
3322     }
3323     return (ret);
3324 }
3325
3326 /************************************************************************
3327  *                                                                      *
3328  *                      Parsing functions                               *
3329  *                                                                      *
3330  ************************************************************************/
3331
3332 static xmlRelaxNGDefinePtr xmlRelaxNGParseAttribute(xmlRelaxNGParserCtxtPtr
3333                                                     ctxt, xmlNodePtr node);
3334 static xmlRelaxNGDefinePtr xmlRelaxNGParseElement(xmlRelaxNGParserCtxtPtr
3335                                                   ctxt, xmlNodePtr node);
3336 static xmlRelaxNGDefinePtr xmlRelaxNGParsePatterns(xmlRelaxNGParserCtxtPtr
3337                                                    ctxt, xmlNodePtr nodes,
3338                                                    int group);
3339 static xmlRelaxNGDefinePtr xmlRelaxNGParsePattern(xmlRelaxNGParserCtxtPtr
3340                                                   ctxt, xmlNodePtr node);
3341 static xmlRelaxNGPtr xmlRelaxNGParseDocument(xmlRelaxNGParserCtxtPtr ctxt,
3342                                              xmlNodePtr node);
3343 static int xmlRelaxNGParseGrammarContent(xmlRelaxNGParserCtxtPtr ctxt,
3344                                          xmlNodePtr nodes);
3345 static xmlRelaxNGDefinePtr xmlRelaxNGParseNameClass(xmlRelaxNGParserCtxtPtr
3346                                                     ctxt, xmlNodePtr node,
3347                                                     xmlRelaxNGDefinePtr
3348                                                     def);
3349 static xmlRelaxNGGrammarPtr xmlRelaxNGParseGrammar(xmlRelaxNGParserCtxtPtr
3350                                                    ctxt, xmlNodePtr nodes);
3351 static int xmlRelaxNGElementMatch(xmlRelaxNGValidCtxtPtr ctxt,
3352                                   xmlRelaxNGDefinePtr define,
3353                                   xmlNodePtr elem);
3354
3355
3356 #define IS_BLANK_NODE(n) (xmlRelaxNGIsBlank((n)->content))
3357
3358 /**
3359  * xmlRelaxNGIsNullable:
3360  * @define:  the definition to verify
3361  *
3362  * Check if a definition is nullable.
3363  *
3364  * Returns 1 if yes, 0 if no and -1 in case of error
3365  */
3366 static int
3367 xmlRelaxNGIsNullable(xmlRelaxNGDefinePtr define)
3368 {
3369     int ret;
3370
3371     if (define == NULL)
3372         return (-1);
3373
3374     if (define->dflags & IS_NULLABLE)
3375         return (1);
3376     if (define->dflags & IS_NOT_NULLABLE)
3377         return (0);
3378     switch (define->type) {
3379         case XML_RELAXNG_EMPTY:
3380         case XML_RELAXNG_TEXT:
3381             ret = 1;
3382             break;
3383         case XML_RELAXNG_NOOP:
3384         case XML_RELAXNG_DEF:
3385         case XML_RELAXNG_REF:
3386         case XML_RELAXNG_EXTERNALREF:
3387         case XML_RELAXNG_PARENTREF:
3388         case XML_RELAXNG_ONEORMORE:
3389             ret = xmlRelaxNGIsNullable(define->content);
3390             break;
3391         case XML_RELAXNG_EXCEPT:
3392         case XML_RELAXNG_NOT_ALLOWED:
3393         case XML_RELAXNG_ELEMENT:
3394         case XML_RELAXNG_DATATYPE:
3395         case XML_RELAXNG_PARAM:
3396         case XML_RELAXNG_VALUE:
3397         case XML_RELAXNG_LIST:
3398         case XML_RELAXNG_ATTRIBUTE:
3399             ret = 0;
3400             break;
3401         case XML_RELAXNG_CHOICE:{
3402                 xmlRelaxNGDefinePtr list = define->content;
3403
3404                 while (list != NULL) {
3405                     ret = xmlRelaxNGIsNullable(list);
3406                     if (ret != 0)
3407                         goto done;
3408                     list = list->next;
3409                 }
3410                 ret = 0;
3411                 break;
3412             }
3413         case XML_RELAXNG_START:
3414         case XML_RELAXNG_INTERLEAVE:
3415         case XML_RELAXNG_GROUP:{
3416                 xmlRelaxNGDefinePtr list = define->content;
3417
3418                 while (list != NULL) {
3419                     ret = xmlRelaxNGIsNullable(list);
3420                     if (ret != 1)
3421                         goto done;
3422                     list = list->next;
3423                 }
3424                 return (1);
3425             }
3426         default:
3427             return (-1);
3428     }
3429   done:
3430     if (ret == 0)
3431         define->dflags |= IS_NOT_NULLABLE;
3432     if (ret == 1)
3433         define->dflags |= IS_NULLABLE;
3434     return (ret);
3435 }
3436
3437 /**
3438  * xmlRelaxNGIsBlank:
3439  * @str:  a string
3440  *
3441  * Check if a string is ignorable c.f. 4.2. Whitespace
3442  *
3443  * Returns 1 if the string is NULL or made of blanks chars, 0 otherwise
3444  */
3445 static int
3446 xmlRelaxNGIsBlank(xmlChar * str)
3447 {
3448     if (str == NULL)
3449         return (1);
3450     while (*str != 0) {
3451         if (!(IS_BLANK_CH(*str)))
3452             return (0);
3453         str++;
3454     }
3455     return (1);
3456 }
3457
3458 /**
3459  * xmlRelaxNGGetDataTypeLibrary:
3460  * @ctxt:  a Relax-NG parser context
3461  * @node:  the current data or value element
3462  *
3463  * Applies algorithm from 4.3. datatypeLibrary attribute
3464  *
3465  * Returns the datatypeLibary value or NULL if not found
3466  */
3467 static xmlChar *
3468 xmlRelaxNGGetDataTypeLibrary(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,
3469                              xmlNodePtr node)
3470 {
3471     xmlChar *ret, *escape;
3472
3473     if (node == NULL)
3474         return(NULL);
3475
3476     if ((IS_RELAXNG(node, "data")) || (IS_RELAXNG(node, "value"))) {
3477         ret = xmlGetProp(node, BAD_CAST "datatypeLibrary");
3478         if (ret != NULL) {
3479             if (ret[0] == 0) {
3480                 xmlFree(ret);
3481                 return (NULL);
3482             }
3483             escape = xmlURIEscapeStr(ret, BAD_CAST ":/#?");
3484             if (escape == NULL) {
3485                 return (ret);
3486             }
3487             xmlFree(ret);
3488             return (escape);
3489         }
3490     }
3491     node = node->parent;
3492     while ((node != NULL) && (node->type == XML_ELEMENT_NODE)) {
3493         ret = xmlGetProp(node, BAD_CAST "datatypeLibrary");
3494         if (ret != NULL) {
3495             if (ret[0] == 0) {
3496                 xmlFree(ret);
3497                 return (NULL);
3498             }
3499             escape = xmlURIEscapeStr(ret, BAD_CAST ":/#?");
3500             if (escape == NULL) {
3501                 return (ret);
3502             }
3503             xmlFree(ret);
3504             return (escape);
3505         }
3506         node = node->parent;
3507     }
3508     return (NULL);
3509 }
3510
3511 /**
3512  * xmlRelaxNGParseValue:
3513  * @ctxt:  a Relax-NG parser context
3514  * @node:  the data node.
3515  *
3516  * parse the content of a RelaxNG value node.
3517  *
3518  * Returns the definition pointer or NULL in case of error
3519  */
3520 static xmlRelaxNGDefinePtr
3521 xmlRelaxNGParseValue(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
3522 {
3523     xmlRelaxNGDefinePtr def = NULL;
3524     xmlRelaxNGTypeLibraryPtr lib = NULL;
3525     xmlChar *type;
3526     xmlChar *library;
3527     int success = 0;
3528
3529     def = xmlRelaxNGNewDefine(ctxt, node);
3530     if (def == NULL)
3531         return (NULL);
3532     def->type = XML_RELAXNG_VALUE;
3533
3534     type = xmlGetProp(node, BAD_CAST "type");
3535     if (type != NULL) {
3536         xmlRelaxNGNormExtSpace(type);
3537         if (xmlValidateNCName(type, 0)) {
3538             xmlRngPErr(ctxt, node, XML_RNGP_TYPE_VALUE,
3539                        "value type '%s' is not an NCName\n", type, NULL);
3540         }
3541         library = xmlRelaxNGGetDataTypeLibrary(ctxt, node);
3542         if (library == NULL)
3543             library =
3544                 xmlStrdup(BAD_CAST "http://relaxng.org/ns/structure/1.0");
3545
3546         def->name = type;
3547         def->ns = library;
3548
3549         lib = (xmlRelaxNGTypeLibraryPtr)
3550             xmlHashLookup(xmlRelaxNGRegisteredTypes, library);
3551         if (lib == NULL) {
3552             xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_TYPE_LIB,
3553                        "Use of unregistered type library '%s'\n", library,
3554                        NULL);
3555             def->data = NULL;
3556         } else {
3557             def->data = lib;
3558             if (lib->have == NULL) {
3559                 xmlRngPErr(ctxt, node, XML_RNGP_ERROR_TYPE_LIB,
3560                            "Internal error with type library '%s': no 'have'\n",
3561                            library, NULL);
3562             } else {
3563                 success = lib->have(lib->data, def->name);
3564                 if (success != 1) {
3565                     xmlRngPErr(ctxt, node, XML_RNGP_TYPE_NOT_FOUND,
3566                                "Error type '%s' is not exported by type library '%s'\n",
3567                                def->name, library);
3568                 }
3569             }
3570         }
3571     }
3572     if (node->children == NULL) {
3573         def->value = xmlStrdup(BAD_CAST "");
3574     } else if (((node->children->type != XML_TEXT_NODE) &&
3575                 (node->children->type != XML_CDATA_SECTION_NODE)) ||
3576                (node->children->next != NULL)) {
3577         xmlRngPErr(ctxt, node, XML_RNGP_TEXT_EXPECTED,
3578                    "Expecting a single text value for <value>content\n",
3579                    NULL, NULL);
3580     } else if (def != NULL) {
3581         def->value = xmlNodeGetContent(node);
3582         if (def->value == NULL) {
3583             xmlRngPErr(ctxt, node, XML_RNGP_VALUE_NO_CONTENT,
3584                        "Element <value> has no content\n", NULL, NULL);
3585         } else if ((lib != NULL) && (lib->check != NULL) && (success == 1)) {
3586             void *val = NULL;
3587
3588             success =
3589                 lib->check(lib->data, def->name, def->value, &val, node);
3590             if (success != 1) {
3591                 xmlRngPErr(ctxt, node, XML_RNGP_INVALID_VALUE,
3592                            "Value '%s' is not acceptable for type '%s'\n",
3593                            def->value, def->name);
3594             } else {
3595                 if (val != NULL)
3596                     def->attrs = val;
3597             }
3598         }
3599     }
3600     return (def);
3601 }
3602
3603 /**
3604  * xmlRelaxNGParseData:
3605  * @ctxt:  a Relax-NG parser context
3606  * @node:  the data node.
3607  *
3608  * parse the content of a RelaxNG data node.
3609  *
3610  * Returns the definition pointer or NULL in case of error
3611  */
3612 static xmlRelaxNGDefinePtr
3613 xmlRelaxNGParseData(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
3614 {
3615     xmlRelaxNGDefinePtr def = NULL, except;
3616     xmlRelaxNGDefinePtr param, lastparam = NULL;
3617     xmlRelaxNGTypeLibraryPtr lib;
3618     xmlChar *type;
3619     xmlChar *library;
3620     xmlNodePtr content;
3621     int tmp;
3622
3623     type = xmlGetProp(node, BAD_CAST "type");
3624     if (type == NULL) {
3625         xmlRngPErr(ctxt, node, XML_RNGP_TYPE_MISSING, "data has no type\n", NULL,
3626                    NULL);
3627         return (NULL);
3628     }
3629     xmlRelaxNGNormExtSpace(type);
3630     if (xmlValidateNCName(type, 0)) {
3631         xmlRngPErr(ctxt, node, XML_RNGP_TYPE_VALUE,
3632                    "data type '%s' is not an NCName\n", type, NULL);
3633     }
3634     library = xmlRelaxNGGetDataTypeLibrary(ctxt, node);
3635     if (library == NULL)
3636         library =
3637             xmlStrdup(BAD_CAST "http://relaxng.org/ns/structure/1.0");
3638
3639     def = xmlRelaxNGNewDefine(ctxt, node);
3640     if (def == NULL) {
3641         xmlFree(type);
3642         return (NULL);
3643     }
3644     def->type = XML_RELAXNG_DATATYPE;
3645     def->name = type;
3646     def->ns = library;
3647
3648     lib = (xmlRelaxNGTypeLibraryPtr)
3649         xmlHashLookup(xmlRelaxNGRegisteredTypes, library);
3650     if (lib == NULL) {
3651         xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_TYPE_LIB,
3652                    "Use of unregistered type library '%s'\n", library,
3653                    NULL);
3654         def->data = NULL;
3655     } else {
3656         def->data = lib;
3657         if (lib->have == NULL) {
3658             xmlRngPErr(ctxt, node, XML_RNGP_ERROR_TYPE_LIB,
3659                        "Internal error with type library '%s': no 'have'\n",
3660                        library, NULL);
3661         } else {
3662             tmp = lib->have(lib->data, def->name);
3663             if (tmp != 1) {
3664                 xmlRngPErr(ctxt, node, XML_RNGP_TYPE_NOT_FOUND,
3665                            "Error type '%s' is not exported by type library '%s'\n",
3666                            def->name, library);
3667             } else
3668                 if ((xmlStrEqual
3669                      (library,
3670                       BAD_CAST
3671                       "http://www.w3.org/2001/XMLSchema-datatypes"))
3672                     && ((xmlStrEqual(def->name, BAD_CAST "IDREF"))
3673                         || (xmlStrEqual(def->name, BAD_CAST "IDREFS")))) {
3674                 ctxt->idref = 1;
3675             }
3676         }
3677     }
3678     content = node->children;
3679
3680     /*
3681      * Handle optional params
3682      */
3683     while (content != NULL) {
3684         if (!xmlStrEqual(content->name, BAD_CAST "param"))
3685             break;
3686         if (xmlStrEqual(library,
3687                         BAD_CAST "http://relaxng.org/ns/structure/1.0")) {
3688             xmlRngPErr(ctxt, node, XML_RNGP_PARAM_FORBIDDEN,
3689                        "Type library '%s' does not allow type parameters\n",
3690                        library, NULL);
3691             content = content->next;
3692             while ((content != NULL) &&
3693                    (xmlStrEqual(content->name, BAD_CAST "param")))
3694                 content = content->next;
3695         } else {
3696             param = xmlRelaxNGNewDefine(ctxt, node);
3697             if (param != NULL) {
3698                 param->type = XML_RELAXNG_PARAM;
3699                 param->name = xmlGetProp(content, BAD_CAST "name");
3700                 if (param->name == NULL) {
3701                     xmlRngPErr(ctxt, node, XML_RNGP_PARAM_NAME_MISSING,
3702                                "param has no name\n", NULL, NULL);
3703                 }
3704                 param->value = xmlNodeGetContent(content);
3705                 if (lastparam == NULL) {
3706                     def->attrs = lastparam = param;
3707                 } else {
3708                     lastparam->next = param;
3709                     lastparam = param;
3710                 }
3711                 if (lib != NULL) {
3712                 }
3713             }
3714             content = content->next;
3715         }
3716     }
3717     /*
3718      * Handle optional except
3719      */
3720     if ((content != NULL)
3721         && (xmlStrEqual(content->name, BAD_CAST "except"))) {
3722         xmlNodePtr child;
3723         xmlRelaxNGDefinePtr tmp2, last = NULL;
3724
3725         except = xmlRelaxNGNewDefine(ctxt, node);
3726         if (except == NULL) {
3727             return (def);
3728         }
3729         except->type = XML_RELAXNG_EXCEPT;
3730         child = content->children;
3731         def->content = except;
3732         if (child == NULL) {
3733             xmlRngPErr(ctxt, content, XML_RNGP_EXCEPT_NO_CONTENT,
3734                        "except has no content\n", NULL, NULL);
3735         }
3736         while (child != NULL) {
3737             tmp2 = xmlRelaxNGParsePattern(ctxt, child);
3738             if (tmp2 != NULL) {
3739                 if (last == NULL) {
3740                     except->content = last = tmp2;
3741                 } else {
3742                     last->next = tmp2;
3743                     last = tmp2;
3744                 }
3745             }
3746             child = child->next;
3747         }
3748         content = content->next;
3749     }
3750     /*
3751      * Check there is no unhandled data
3752      */
3753     if (content != NULL) {
3754         xmlRngPErr(ctxt, content, XML_RNGP_DATA_CONTENT,
3755                    "Element data has unexpected content %s\n",
3756                    content->name, NULL);
3757     }
3758
3759     return (def);
3760 }
3761
3762 static const xmlChar *invalidName = BAD_CAST "\1";
3763
3764 /**
3765  * xmlRelaxNGCompareNameClasses:
3766  * @defs1:  the first element/attribute defs
3767  * @defs2:  the second element/attribute defs
3768  * @name:  the restriction on the name
3769  * @ns:  the restriction on the namespace
3770  *
3771  * Compare the 2 lists of element definitions. The comparison is
3772  * that if both lists do not accept the same QNames, it returns 1
3773  * If the 2 lists can accept the same QName the comparison returns 0
3774  *
3775  * Returns 1 disttinct, 0 if equal
3776  */
3777 static int
3778 xmlRelaxNGCompareNameClasses(xmlRelaxNGDefinePtr def1,
3779                              xmlRelaxNGDefinePtr def2)
3780 {
3781     int ret = 1;
3782     xmlNode node;
3783     xmlNs ns;
3784     xmlRelaxNGValidCtxt ctxt;
3785
3786     memset(&ctxt, 0, sizeof(xmlRelaxNGValidCtxt));
3787
3788     ctxt.flags = FLAGS_IGNORABLE | FLAGS_NOERROR;
3789
3790     if ((def1->type == XML_RELAXNG_ELEMENT) ||
3791         (def1->type == XML_RELAXNG_ATTRIBUTE)) {
3792         if (def2->type == XML_RELAXNG_TEXT)
3793             return (1);
3794         if (def1->name != NULL) {
3795             node.name = def1->name;
3796         } else {
3797             node.name = invalidName;
3798         }
3799         if (def1->ns != NULL) {
3800             if (def1->ns[0] == 0) {
3801                 node.ns = NULL;
3802             } else {
3803                 node.ns = &ns;
3804                 ns.href = def1->ns;
3805             }
3806         } else {
3807             node.ns = NULL;
3808         }
3809         if (xmlRelaxNGElementMatch(&ctxt, def2, &node)) {
3810             if (def1->nameClass != NULL) {
3811                 ret = xmlRelaxNGCompareNameClasses(def1->nameClass, def2);
3812             } else {
3813                 ret = 0;
3814             }
3815         } else {
3816             ret = 1;
3817         }
3818     } else if (def1->type == XML_RELAXNG_TEXT) {
3819         if (def2->type == XML_RELAXNG_TEXT)
3820             return (0);
3821         return (1);
3822     } else if (def1->type == XML_RELAXNG_EXCEPT) {
3823         ret = xmlRelaxNGCompareNameClasses(def1->content, def2);
3824         if (ret == 0)
3825             ret = 1;
3826         else if (ret == 1)
3827             ret = 0;
3828     } else {
3829         TODO ret = 0;
3830     }
3831     if (ret == 0)
3832         return (ret);
3833     if ((def2->type == XML_RELAXNG_ELEMENT) ||
3834         (def2->type == XML_RELAXNG_ATTRIBUTE)) {
3835         if (def2->name != NULL) {
3836             node.name = def2->name;
3837         } else {
3838             node.name = invalidName;
3839         }
3840         node.ns = &ns;
3841         if (def2->ns != NULL) {
3842             if (def2->ns[0] == 0) {
3843                 node.ns = NULL;
3844             } else {
3845                 ns.href = def2->ns;
3846             }
3847         } else {
3848             ns.href = invalidName;
3849         }
3850         if (xmlRelaxNGElementMatch(&ctxt, def1, &node)) {
3851             if (def2->nameClass != NULL) {
3852                 ret = xmlRelaxNGCompareNameClasses(def2->nameClass, def1);
3853             } else {
3854                 ret = 0;
3855             }
3856         } else {
3857             ret = 1;
3858         }
3859     } else {
3860         TODO ret = 0;
3861     }
3862
3863     return (ret);
3864 }
3865
3866 /**
3867  * xmlRelaxNGCompareElemDefLists:
3868  * @ctxt:  a Relax-NG parser context
3869  * @defs1:  the first list of element/attribute defs
3870  * @defs2:  the second list of element/attribute defs
3871  *
3872  * Compare the 2 lists of element or attribute definitions. The comparison
3873  * is that if both lists do not accept the same QNames, it returns 1
3874  * If the 2 lists can accept the same QName the comparison returns 0
3875  *
3876  * Returns 1 disttinct, 0 if equal
3877  */
3878 static int
3879 xmlRelaxNGCompareElemDefLists(xmlRelaxNGParserCtxtPtr ctxt
3880                               ATTRIBUTE_UNUSED, xmlRelaxNGDefinePtr * def1,
3881                               xmlRelaxNGDefinePtr * def2)
3882 {
3883     xmlRelaxNGDefinePtr *basedef2 = def2;
3884
3885     if ((def1 == NULL) || (def2 == NULL))
3886         return (1);
3887     if ((*def1 == NULL) || (*def2 == NULL))
3888         return (1);
3889     while (*def1 != NULL) {
3890         while ((*def2) != NULL) {
3891             if (xmlRelaxNGCompareNameClasses(*def1, *def2) == 0)
3892                 return (0);
3893             def2++;
3894         }
3895         def2 = basedef2;
3896         def1++;
3897     }
3898     return (1);
3899 }
3900
3901 /**
3902  * xmlRelaxNGGenerateAttributes:
3903  * @ctxt:  a Relax-NG parser context
3904  * @def:  the definition definition
3905  *
3906  * Check if the definition can only generate attributes
3907  *
3908  * Returns 1 if yes, 0 if no and -1 in case of error.
3909  */
3910 static int
3911 xmlRelaxNGGenerateAttributes(xmlRelaxNGParserCtxtPtr ctxt,
3912                              xmlRelaxNGDefinePtr def)
3913 {
3914     xmlRelaxNGDefinePtr parent, cur, tmp;
3915
3916     /*
3917      * Don't run that check in case of error. Infinite recursion
3918      * becomes possible.
3919      */
3920     if (ctxt->nbErrors != 0)
3921         return (-1);
3922
3923     parent = NULL;
3924     cur = def;
3925     while (cur != NULL) {
3926         if ((cur->type == XML_RELAXNG_ELEMENT) ||
3927             (cur->type == XML_RELAXNG_TEXT) ||
3928             (cur->type == XML_RELAXNG_DATATYPE) ||
3929             (cur->type == XML_RELAXNG_PARAM) ||
3930             (cur->type == XML_RELAXNG_LIST) ||
3931             (cur->type == XML_RELAXNG_VALUE) ||
3932             (cur->type == XML_RELAXNG_EMPTY))
3933             return (0);
3934         if ((cur->type == XML_RELAXNG_CHOICE) ||
3935             (cur->type == XML_RELAXNG_INTERLEAVE) ||
3936             (cur->type == XML_RELAXNG_GROUP) ||
3937             (cur->type == XML_RELAXNG_ONEORMORE) ||
3938             (cur->type == XML_RELAXNG_ZEROORMORE) ||
3939             (cur->type == XML_RELAXNG_OPTIONAL) ||
3940             (cur->type == XML_RELAXNG_PARENTREF) ||
3941             (cur->type == XML_RELAXNG_EXTERNALREF) ||
3942             (cur->type == XML_RELAXNG_REF) ||
3943             (cur->type == XML_RELAXNG_DEF)) {
3944             if (cur->content != NULL) {
3945                 parent = cur;
3946                 cur = cur->content;
3947                 tmp = cur;
3948                 while (tmp != NULL) {
3949                     tmp->parent = parent;
3950                     tmp = tmp->next;
3951                 }
3952                 continue;
3953             }
3954         }
3955         if (cur == def)
3956             break;
3957         if (cur->next != NULL) {
3958             cur = cur->next;
3959             continue;
3960         }
3961         do {
3962             cur = cur->parent;
3963             if (cur == NULL)
3964                 break;
3965             if (cur == def)
3966                 return (1);
3967             if (cur->next != NULL) {
3968                 cur = cur->next;
3969                 break;
3970             }
3971         } while (cur != NULL);
3972     }
3973     return (1);
3974 }
3975
3976 /**
3977  * xmlRelaxNGGetElements:
3978  * @ctxt:  a Relax-NG parser context
3979  * @def:  the definition definition
3980  * @eora:  gather elements (0) or attributes (1)
3981  *
3982  * Compute the list of top elements a definition can generate
3983  *
3984  * Returns a list of elements or NULL if none was found.
3985  */
3986 static xmlRelaxNGDefinePtr *
3987 xmlRelaxNGGetElements(xmlRelaxNGParserCtxtPtr ctxt,
3988                       xmlRelaxNGDefinePtr def, int eora)
3989 {
3990     xmlRelaxNGDefinePtr *ret = NULL, parent, cur, tmp;
3991     int len = 0;
3992     int max = 0;
3993
3994     /*
3995      * Don't run that check in case of error. Infinite recursion
3996      * becomes possible.
3997      */
3998     if (ctxt->nbErrors != 0)
3999         return (NULL);
4000
4001     parent = NULL;
4002     cur = def;
4003     while (cur != NULL) {
4004         if (((eora == 0) && ((cur->type == XML_RELAXNG_ELEMENT) ||
4005                              (cur->type == XML_RELAXNG_TEXT))) ||
4006             ((eora == 1) && (cur->type == XML_RELAXNG_ATTRIBUTE))) {
4007             if (ret == NULL) {
4008                 max = 10;
4009                 ret = (xmlRelaxNGDefinePtr *)
4010                     xmlMalloc((max + 1) * sizeof(xmlRelaxNGDefinePtr));
4011                 if (ret == NULL) {
4012                     xmlRngPErrMemory(ctxt, "getting element list\n");
4013                     return (NULL);
4014                 }
4015             } else if (max <= len) {
4016                 xmlRelaxNGDefinePtr *temp;
4017
4018                 max *= 2;
4019                 temp = xmlRealloc(ret,
4020                                (max + 1) * sizeof(xmlRelaxNGDefinePtr));
4021                 if (temp == NULL) {
4022                     xmlRngPErrMemory(ctxt, "getting element list\n");
4023                     xmlFree(ret);
4024                     return (NULL);
4025                 }
4026                 ret = temp;
4027             }
4028             ret[len++] = cur;
4029             ret[len] = NULL;
4030         } else if ((cur->type == XML_RELAXNG_CHOICE) ||
4031                    (cur->type == XML_RELAXNG_INTERLEAVE) ||
4032                    (cur->type == XML_RELAXNG_GROUP) ||
4033                    (cur->type == XML_RELAXNG_ONEORMORE) ||
4034                    (cur->type == XML_RELAXNG_ZEROORMORE) ||
4035                    (cur->type == XML_RELAXNG_OPTIONAL) ||
4036                    (cur->type == XML_RELAXNG_PARENTREF) ||
4037                    (cur->type == XML_RELAXNG_REF) ||
4038                    (cur->type == XML_RELAXNG_DEF) ||
4039                    (cur->type == XML_RELAXNG_EXTERNALREF)) {
4040             /*
4041              * Don't go within elements or attributes or string values.
4042              * Just gather the element top list
4043              */
4044             if (cur->content != NULL) {
4045                 parent = cur;
4046                 cur = cur->content;
4047                 tmp = cur;
4048                 while (tmp != NULL) {
4049                     tmp->parent = parent;
4050                     tmp = tmp->next;
4051                 }
4052                 continue;
4053             }
4054         }
4055         if (cur == def)
4056             break;
4057         if (cur->next != NULL) {
4058             cur = cur->next;
4059             continue;
4060         }
4061         do {
4062             cur = cur->parent;
4063             if (cur == NULL)
4064                 break;
4065             if (cur == def)
4066                 return (ret);
4067             if (cur->next != NULL) {
4068                 cur = cur->next;
4069                 break;
4070             }
4071         } while (cur != NULL);
4072     }
4073     return (ret);
4074 }
4075
4076 /**
4077  * xmlRelaxNGCheckChoiceDeterminism:
4078  * @ctxt:  a Relax-NG parser context
4079  * @def:  the choice definition
4080  *
4081  * Also used to find indeterministic pattern in choice
4082  */
4083 static void
4084 xmlRelaxNGCheckChoiceDeterminism(xmlRelaxNGParserCtxtPtr ctxt,
4085                                  xmlRelaxNGDefinePtr def)
4086 {
4087     xmlRelaxNGDefinePtr **list;
4088     xmlRelaxNGDefinePtr cur;
4089     int nbchild = 0, i, j, ret;
4090     int is_nullable = 0;
4091     int is_indeterminist = 0;
4092     xmlHashTablePtr triage = NULL;
4093     int is_triable = 1;
4094
4095     if ((def == NULL) || (def->type != XML_RELAXNG_CHOICE))
4096         return;
4097
4098     if (def->dflags & IS_PROCESSED)
4099         return;
4100
4101     /*
4102      * Don't run that check in case of error. Infinite recursion
4103      * becomes possible.
4104      */
4105     if (ctxt->nbErrors != 0)
4106         return;
4107
4108     is_nullable = xmlRelaxNGIsNullable(def);
4109
4110     cur = def->content;
4111     while (cur != NULL) {
4112         nbchild++;
4113         cur = cur->next;
4114     }
4115
4116     list = (xmlRelaxNGDefinePtr **) xmlMalloc(nbchild *
4117                                               sizeof(xmlRelaxNGDefinePtr
4118                                                      *));
4119     if (list == NULL) {
4120         xmlRngPErrMemory(ctxt, "building choice\n");
4121         return;
4122     }
4123     i = 0;
4124     /*
4125      * a bit strong but safe
4126      */
4127     if (is_nullable == 0) {
4128         triage = xmlHashCreate(10);
4129     } else {
4130         is_triable = 0;
4131     }
4132     cur = def->content;
4133     while (cur != NULL) {
4134         list[i] = xmlRelaxNGGetElements(ctxt, cur, 0);
4135         if ((list[i] == NULL) || (list[i][0] == NULL)) {
4136             is_triable = 0;
4137         } else if (is_triable == 1) {
4138             xmlRelaxNGDefinePtr *tmp;
4139             int res;
4140
4141             tmp = list[i];
4142             while ((*tmp != NULL) && (is_triable == 1)) {
4143                 if ((*tmp)->type == XML_RELAXNG_TEXT) {
4144                     res = xmlHashAddEntry2(triage,
4145                                            BAD_CAST "#text", NULL,
4146                                            (void *) cur);
4147                     if (res != 0)
4148                         is_triable = -1;
4149                 } else if (((*tmp)->type == XML_RELAXNG_ELEMENT) &&
4150                            ((*tmp)->name != NULL)) {
4151                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4152                         res = xmlHashAddEntry2(triage,
4153                                                (*tmp)->name, NULL,
4154                                                (void *) cur);
4155                     else
4156                         res = xmlHashAddEntry2(triage,
4157                                                (*tmp)->name, (*tmp)->ns,
4158                                                (void *) cur);
4159                     if (res != 0)
4160                         is_triable = -1;
4161                 } else if ((*tmp)->type == XML_RELAXNG_ELEMENT) {
4162                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4163                         res = xmlHashAddEntry2(triage,
4164                                                BAD_CAST "#any", NULL,
4165                                                (void *) cur);
4166                     else
4167                         res = xmlHashAddEntry2(triage,
4168                                                BAD_CAST "#any", (*tmp)->ns,
4169                                                (void *) cur);
4170                     if (res != 0)
4171                         is_triable = -1;
4172                 } else {
4173                     is_triable = -1;
4174                 }
4175                 tmp++;
4176             }
4177         }
4178         i++;
4179         cur = cur->next;
4180     }
4181
4182     for (i = 0; i < nbchild; i++) {
4183         if (list[i] == NULL)
4184             continue;
4185         for (j = 0; j < i; j++) {
4186             if (list[j] == NULL)
4187                 continue;
4188             ret = xmlRelaxNGCompareElemDefLists(ctxt, list[i], list[j]);
4189             if (ret == 0) {
4190                 is_indeterminist = 1;
4191             }
4192         }
4193     }
4194     for (i = 0; i < nbchild; i++) {
4195         if (list[i] != NULL)
4196             xmlFree(list[i]);
4197     }
4198
4199     xmlFree(list);
4200     if (is_indeterminist) {
4201         def->dflags |= IS_INDETERMINIST;
4202     }
4203     if (is_triable == 1) {
4204         def->dflags |= IS_TRIABLE;
4205         def->data = triage;
4206     } else if (triage != NULL) {
4207         xmlHashFree(triage, NULL);
4208     }
4209     def->dflags |= IS_PROCESSED;
4210 }
4211
4212 /**
4213  * xmlRelaxNGCheckGroupAttrs:
4214  * @ctxt:  a Relax-NG parser context
4215  * @def:  the group definition
4216  *
4217  * Detects violations of rule 7.3
4218  */
4219 static void
4220 xmlRelaxNGCheckGroupAttrs(xmlRelaxNGParserCtxtPtr ctxt,
4221                           xmlRelaxNGDefinePtr def)
4222 {
4223     xmlRelaxNGDefinePtr **list;
4224     xmlRelaxNGDefinePtr cur;
4225     int nbchild = 0, i, j, ret;
4226
4227     if ((def == NULL) ||
4228         ((def->type != XML_RELAXNG_GROUP) &&
4229          (def->type != XML_RELAXNG_ELEMENT)))
4230         return;
4231
4232     if (def->dflags & IS_PROCESSED)
4233         return;
4234
4235     /*
4236      * Don't run that check in case of error. Infinite recursion
4237      * becomes possible.
4238      */
4239     if (ctxt->nbErrors != 0)
4240         return;
4241
4242     cur = def->attrs;
4243     while (cur != NULL) {
4244         nbchild++;
4245         cur = cur->next;
4246     }
4247     cur = def->content;
4248     while (cur != NULL) {
4249         nbchild++;
4250         cur = cur->next;
4251     }
4252
4253     list = (xmlRelaxNGDefinePtr **) xmlMalloc(nbchild *
4254                                               sizeof(xmlRelaxNGDefinePtr
4255                                                      *));
4256     if (list == NULL) {
4257         xmlRngPErrMemory(ctxt, "building group\n");
4258         return;
4259     }
4260     i = 0;
4261     cur = def->attrs;
4262     while (cur != NULL) {
4263         list[i] = xmlRelaxNGGetElements(ctxt, cur, 1);
4264         i++;
4265         cur = cur->next;
4266     }
4267     cur = def->content;
4268     while (cur != NULL) {
4269         list[i] = xmlRelaxNGGetElements(ctxt, cur, 1);
4270         i++;
4271         cur = cur->next;
4272     }
4273
4274     for (i = 0; i < nbchild; i++) {
4275         if (list[i] == NULL)
4276             continue;
4277         for (j = 0; j < i; j++) {
4278             if (list[j] == NULL)
4279                 continue;
4280             ret = xmlRelaxNGCompareElemDefLists(ctxt, list[i], list[j]);
4281             if (ret == 0) {
4282                 xmlRngPErr(ctxt, def->node, XML_RNGP_GROUP_ATTR_CONFLICT,
4283                            "Attributes conflicts in group\n", NULL, NULL);
4284             }
4285         }
4286     }
4287     for (i = 0; i < nbchild; i++) {
4288         if (list[i] != NULL)
4289             xmlFree(list[i]);
4290     }
4291
4292     xmlFree(list);
4293     def->dflags |= IS_PROCESSED;
4294 }
4295
4296 /**
4297  * xmlRelaxNGComputeInterleaves:
4298  * @def:  the interleave definition
4299  * @ctxt:  a Relax-NG parser context
4300  * @name:  the definition name
4301  *
4302  * A lot of work for preprocessing interleave definitions
4303  * is potentially needed to get a decent execution speed at runtime
4304  *   - trying to get a total order on the element nodes generated
4305  *     by the interleaves, order the list of interleave definitions
4306  *     following that order.
4307  *   - if <text/> is used to handle mixed content, it is better to
4308  *     flag this in the define and simplify the runtime checking
4309  *     algorithm
4310  */
4311 static void
4312 xmlRelaxNGComputeInterleaves(xmlRelaxNGDefinePtr def,
4313                              xmlRelaxNGParserCtxtPtr ctxt,
4314                              xmlChar * name ATTRIBUTE_UNUSED)
4315 {
4316     xmlRelaxNGDefinePtr cur, *tmp;
4317
4318     xmlRelaxNGPartitionPtr partitions = NULL;
4319     xmlRelaxNGInterleaveGroupPtr *groups = NULL;
4320     xmlRelaxNGInterleaveGroupPtr group;
4321     int i, j, ret, res;
4322     int nbgroups = 0;
4323     int nbchild = 0;
4324     int is_mixed = 0;
4325     int is_determinist = 1;
4326
4327     /*
4328      * Don't run that check in case of error. Infinite recursion
4329      * becomes possible.
4330      */
4331     if (ctxt->nbErrors != 0)
4332         return;
4333
4334 #ifdef DEBUG_INTERLEAVE
4335     xmlGenericError(xmlGenericErrorContext,
4336                     "xmlRelaxNGComputeInterleaves(%s)\n", name);
4337 #endif
4338     cur = def->content;
4339     while (cur != NULL) {
4340         nbchild++;
4341         cur = cur->next;
4342     }
4343
4344 #ifdef DEBUG_INTERLEAVE
4345     xmlGenericError(xmlGenericErrorContext, "  %d child\n", nbchild);
4346 #endif
4347     groups = (xmlRelaxNGInterleaveGroupPtr *)
4348         xmlMalloc(nbchild * sizeof(xmlRelaxNGInterleaveGroupPtr));
4349     if (groups == NULL)
4350         goto error;
4351     cur = def->content;
4352     while (cur != NULL) {
4353         groups[nbgroups] = (xmlRelaxNGInterleaveGroupPtr)
4354             xmlMalloc(sizeof(xmlRelaxNGInterleaveGroup));
4355         if (groups[nbgroups] == NULL)
4356             goto error;
4357         if (cur->type == XML_RELAXNG_TEXT)
4358             is_mixed++;
4359         groups[nbgroups]->rule = cur;
4360         groups[nbgroups]->defs = xmlRelaxNGGetElements(ctxt, cur, 0);
4361         groups[nbgroups]->attrs = xmlRelaxNGGetElements(ctxt, cur, 1);
4362         nbgroups++;
4363         cur = cur->next;
4364     }
4365 #ifdef DEBUG_INTERLEAVE
4366     xmlGenericError(xmlGenericErrorContext, "  %d groups\n", nbgroups);
4367 #endif
4368
4369     /*
4370      * Let's check that all rules makes a partitions according to 7.4
4371      */
4372     partitions = (xmlRelaxNGPartitionPtr)
4373         xmlMalloc(sizeof(xmlRelaxNGPartition));
4374     if (partitions == NULL)
4375         goto error;
4376     memset(partitions, 0, sizeof(xmlRelaxNGPartition));
4377     partitions->nbgroups = nbgroups;
4378     partitions->triage = xmlHashCreate(nbgroups);
4379     for (i = 0; i < nbgroups; i++) {
4380         group = groups[i];
4381         for (j = i + 1; j < nbgroups; j++) {
4382             if (groups[j] == NULL)
4383                 continue;
4384
4385             ret = xmlRelaxNGCompareElemDefLists(ctxt, group->defs,
4386                                                 groups[j]->defs);
4387             if (ret == 0) {
4388                 xmlRngPErr(ctxt, def->node, XML_RNGP_ELEM_TEXT_CONFLICT,
4389                            "Element or text conflicts in interleave\n",
4390                            NULL, NULL);
4391             }
4392             ret = xmlRelaxNGCompareElemDefLists(ctxt, group->attrs,
4393                                                 groups[j]->attrs);
4394             if (ret == 0) {
4395                 xmlRngPErr(ctxt, def->node, XML_RNGP_ATTR_CONFLICT,
4396                            "Attributes conflicts in interleave\n", NULL,
4397                            NULL);
4398             }
4399         }
4400         tmp = group->defs;
4401         if ((tmp != NULL) && (*tmp != NULL)) {
4402             while (*tmp != NULL) {
4403                 if ((*tmp)->type == XML_RELAXNG_TEXT) {
4404                     res = xmlHashAddEntry2(partitions->triage,
4405                                            BAD_CAST "#text", NULL,
4406                                            (void *) (long) (i + 1));
4407                     if (res != 0)
4408                         is_determinist = -1;
4409                 } else if (((*tmp)->type == XML_RELAXNG_ELEMENT) &&
4410                            ((*tmp)->name != NULL)) {
4411                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4412                         res = xmlHashAddEntry2(partitions->triage,
4413                                                (*tmp)->name, NULL,
4414                                                (void *) (long) (i + 1));
4415                     else
4416                         res = xmlHashAddEntry2(partitions->triage,
4417                                                (*tmp)->name, (*tmp)->ns,
4418                                                (void *) (long) (i + 1));
4419                     if (res != 0)
4420                         is_determinist = -1;
4421                 } else if ((*tmp)->type == XML_RELAXNG_ELEMENT) {
4422                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4423                         res = xmlHashAddEntry2(partitions->triage,
4424                                                BAD_CAST "#any", NULL,
4425                                                (void *) (long) (i + 1));
4426                     else
4427                         res = xmlHashAddEntry2(partitions->triage,
4428                                                BAD_CAST "#any", (*tmp)->ns,
4429                                                (void *) (long) (i + 1));
4430                     if ((*tmp)->nameClass != NULL)
4431                         is_determinist = 2;
4432                     if (res != 0)
4433                         is_determinist = -1;
4434                 } else {
4435                     is_determinist = -1;
4436                 }
4437                 tmp++;
4438             }
4439         } else {
4440             is_determinist = 0;
4441         }
4442     }
4443     partitions->groups = groups;
4444
4445     /*
4446      * and save the partition list back in the def
4447      */
4448     def->data = partitions;
4449     if (is_mixed != 0)
4450         def->dflags |= IS_MIXED;
4451     if (is_determinist == 1)
4452         partitions->flags = IS_DETERMINIST;
4453     if (is_determinist == 2)
4454         partitions->flags = IS_DETERMINIST | IS_NEEDCHECK;
4455     return;
4456
4457   error:
4458     xmlRngPErrMemory(ctxt, "in interleave computation\n");
4459     if (groups != NULL) {
4460         for (i = 0; i < nbgroups; i++)
4461             if (groups[i] != NULL) {
4462                 if (groups[i]->defs != NULL)
4463                     xmlFree(groups[i]->defs);
4464                 xmlFree(groups[i]);
4465             }
4466         xmlFree(groups);
4467     }
4468     xmlRelaxNGFreePartition(partitions);
4469 }
4470
4471 /**
4472  * xmlRelaxNGParseInterleave:
4473  * @ctxt:  a Relax-NG parser context
4474  * @node:  the data node.
4475  *
4476  * parse the content of a RelaxNG interleave node.
4477  *
4478  * Returns the definition pointer or NULL in case of error
4479  */
4480 static xmlRelaxNGDefinePtr
4481 xmlRelaxNGParseInterleave(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4482 {
4483     xmlRelaxNGDefinePtr def = NULL;
4484     xmlRelaxNGDefinePtr last = NULL, cur;
4485     xmlNodePtr child;
4486
4487     def = xmlRelaxNGNewDefine(ctxt, node);
4488     if (def == NULL) {
4489         return (NULL);
4490     }
4491     def->type = XML_RELAXNG_INTERLEAVE;
4492
4493     if (ctxt->interleaves == NULL)
4494         ctxt->interleaves = xmlHashCreate(10);
4495     if (ctxt->interleaves == NULL) {
4496         xmlRngPErrMemory(ctxt, "create interleaves\n");
4497     } else {
4498         char name[32];
4499
4500         snprintf(name, 32, "interleave%d", ctxt->nbInterleaves++);
4501         if (xmlHashAddEntry(ctxt->interleaves, BAD_CAST name, def) < 0) {
4502             xmlRngPErr(ctxt, node, XML_RNGP_INTERLEAVE_ADD,
4503                        "Failed to add %s to hash table\n",
4504                        (const xmlChar *) name, NULL);
4505         }
4506     }
4507     child = node->children;
4508     if (child == NULL) {
4509         xmlRngPErr(ctxt, node, XML_RNGP_INTERLEAVE_NO_CONTENT,
4510                    "Element interleave is empty\n", NULL, NULL);
4511     }
4512     while (child != NULL) {
4513         if (IS_RELAXNG(child, "element")) {
4514             cur = xmlRelaxNGParseElement(ctxt, child);
4515         } else {
4516             cur = xmlRelaxNGParsePattern(ctxt, child);
4517         }
4518         if (cur != NULL) {
4519             cur->parent = def;
4520             if (last == NULL) {
4521                 def->content = last = cur;
4522             } else {
4523                 last->next = cur;
4524                 last = cur;
4525             }
4526         }
4527         child = child->next;
4528     }
4529
4530     return (def);
4531 }
4532
4533 /**
4534  * xmlRelaxNGParseInclude:
4535  * @ctxt:  a Relax-NG parser context
4536  * @node:  the include node
4537  *
4538  * Integrate the content of an include node in the current grammar
4539  *
4540  * Returns 0 in case of success or -1 in case of error
4541  */
4542 static int
4543 xmlRelaxNGParseInclude(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4544 {
4545     xmlRelaxNGIncludePtr incl;
4546     xmlNodePtr root;
4547     int ret = 0, tmp;
4548
4549     incl = node->psvi;
4550     if (incl == NULL) {
4551         xmlRngPErr(ctxt, node, XML_RNGP_INCLUDE_EMPTY,
4552                    "Include node has no data\n", NULL, NULL);
4553         return (-1);
4554     }
4555     root = xmlDocGetRootElement(incl->doc);
4556     if (root == NULL) {
4557         xmlRngPErr(ctxt, node, XML_RNGP_EMPTY, "Include document is empty\n",
4558                    NULL, NULL);
4559         return (-1);
4560     }
4561     if (!xmlStrEqual(root->name, BAD_CAST "grammar")) {
4562         xmlRngPErr(ctxt, node, XML_RNGP_GRAMMAR_MISSING,
4563                    "Include document root is not a grammar\n", NULL, NULL);
4564         return (-1);
4565     }
4566
4567     /*
4568      * Merge the definition from both the include and the internal list
4569      */
4570     if (root->children != NULL) {
4571         tmp = xmlRelaxNGParseGrammarContent(ctxt, root->children);
4572         if (tmp != 0)
4573             ret = -1;
4574     }
4575     if (node->children != NULL) {
4576         tmp = xmlRelaxNGParseGrammarContent(ctxt, node->children);
4577         if (tmp != 0)
4578             ret = -1;
4579     }
4580     return (ret);
4581 }
4582
4583 /**
4584  * xmlRelaxNGParseDefine:
4585  * @ctxt:  a Relax-NG parser context
4586  * @node:  the define node
4587  *
4588  * parse the content of a RelaxNG define element node.
4589  *
4590  * Returns 0 in case of success or -1 in case of error
4591  */
4592 static int
4593 xmlRelaxNGParseDefine(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4594 {
4595     xmlChar *name;
4596     int ret = 0, tmp;
4597     xmlRelaxNGDefinePtr def;
4598     const xmlChar *olddefine;
4599
4600     name = xmlGetProp(node, BAD_CAST "name");
4601     if (name == NULL) {
4602         xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_NAME_MISSING,
4603                    "define has no name\n", NULL, NULL);
4604     } else {
4605         xmlRelaxNGNormExtSpace(name);
4606         if (xmlValidateNCName(name, 0)) {
4607             xmlRngPErr(ctxt, node, XML_RNGP_INVALID_DEFINE_NAME,
4608                        "define name '%s' is not an NCName\n", name, NULL);
4609         }
4610         def = xmlRelaxNGNewDefine(ctxt, node);
4611         if (def == NULL) {
4612             xmlFree(name);
4613             return (-1);
4614         }
4615         def->type = XML_RELAXNG_DEF;
4616         def->name = name;
4617         if (node->children == NULL) {
4618             xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_EMPTY,
4619                        "define has no children\n", NULL, NULL);
4620         } else {
4621             olddefine = ctxt->define;
4622             ctxt->define = name;
4623             def->content =
4624                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4625             ctxt->define = olddefine;
4626         }
4627         if (ctxt->grammar->defs == NULL)
4628             ctxt->grammar->defs = xmlHashCreate(10);
4629         if (ctxt->grammar->defs == NULL) {
4630             xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_CREATE_FAILED,
4631                        "Could not create definition hash\n", NULL, NULL);
4632             ret = -1;
4633         } else {
4634             tmp = xmlHashAddEntry(ctxt->grammar->defs, name, def);
4635             if (tmp < 0) {
4636                 xmlRelaxNGDefinePtr prev;
4637
4638                 prev = xmlHashLookup(ctxt->grammar->defs, name);
4639                 if (prev == NULL) {
4640                     xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_CREATE_FAILED,
4641                                "Internal error on define aggregation of %s\n",
4642                                name, NULL);
4643                     ret = -1;
4644                 } else {
4645                     while (prev->nextHash != NULL)
4646                         prev = prev->nextHash;
4647                     prev->nextHash = def;
4648                 }
4649             }
4650         }
4651     }
4652     return (ret);
4653 }
4654
4655 /**
4656  * xmlRelaxNGParseImportRef:
4657  * @payload: the parser context
4658  * @data: the current grammar
4659  * @name: the reference name
4660  *
4661  * Import import one references into the current grammar
4662  */
4663 static void
4664 xmlRelaxNGParseImportRef(void *payload, void *data, xmlChar *name) {
4665     xmlRelaxNGParserCtxtPtr ctxt = (xmlRelaxNGParserCtxtPtr) data;
4666     xmlRelaxNGDefinePtr def = (xmlRelaxNGDefinePtr) payload;
4667     int tmp;
4668
4669     def->dflags |= IS_EXTERNAL_REF;
4670
4671     tmp = xmlHashAddEntry(ctxt->grammar->refs, name, def);
4672     if (tmp < 0) {
4673         xmlRelaxNGDefinePtr prev;
4674
4675         prev = (xmlRelaxNGDefinePtr)
4676             xmlHashLookup(ctxt->grammar->refs, def->name);
4677         if (prev == NULL) {
4678             if (def->name != NULL) {
4679                 xmlRngPErr(ctxt, NULL, XML_RNGP_REF_CREATE_FAILED,
4680                            "Error refs definitions '%s'\n",
4681                            def->name, NULL);
4682             } else {
4683                 xmlRngPErr(ctxt, NULL, XML_RNGP_REF_CREATE_FAILED,
4684                            "Error refs definitions\n",
4685                            NULL, NULL);
4686             }
4687         } else {
4688             def->nextHash = prev->nextHash;
4689             prev->nextHash = def;
4690         }
4691     }
4692 }
4693
4694 /**
4695  * xmlRelaxNGParseImportRefs:
4696  * @ctxt: the parser context
4697  * @grammar: the sub grammar
4698  *
4699  * Import references from the subgrammar into the current grammar
4700  *
4701  * Returns 0 in case of success, -1 in case of failure
4702  */
4703 static int
4704 xmlRelaxNGParseImportRefs(xmlRelaxNGParserCtxtPtr ctxt,
4705                           xmlRelaxNGGrammarPtr grammar) {
4706     if ((ctxt == NULL) || (grammar == NULL) || (ctxt->grammar == NULL))
4707         return(-1);
4708     if (grammar->refs == NULL)
4709         return(0);
4710     if (ctxt->grammar->refs == NULL)
4711         ctxt->grammar->refs = xmlHashCreate(10);
4712     if (ctxt->grammar->refs == NULL) {
4713         xmlRngPErr(ctxt, NULL, XML_RNGP_REF_CREATE_FAILED,
4714                    "Could not create references hash\n", NULL, NULL);
4715         return(-1);
4716     }
4717     xmlHashScan(grammar->refs, xmlRelaxNGParseImportRef, ctxt);
4718     return(0);
4719 }
4720
4721 /**
4722  * xmlRelaxNGProcessExternalRef:
4723  * @ctxt: the parser context
4724  * @node:  the externlRef node
4725  *
4726  * Process and compile an externlRef node
4727  *
4728  * Returns the xmlRelaxNGDefinePtr or NULL in case of error
4729  */
4730 static xmlRelaxNGDefinePtr
4731 xmlRelaxNGProcessExternalRef(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4732 {
4733     xmlRelaxNGDocumentPtr docu;
4734     xmlNodePtr root, tmp;
4735     xmlChar *ns;
4736     int newNs = 0, oldflags;
4737     xmlRelaxNGDefinePtr def;
4738
4739     docu = node->psvi;
4740     if (docu != NULL) {
4741         def = xmlRelaxNGNewDefine(ctxt, node);
4742         if (def == NULL)
4743             return (NULL);
4744         def->type = XML_RELAXNG_EXTERNALREF;
4745
4746         if (docu->content == NULL) {
4747             /*
4748              * Then do the parsing for good
4749              */
4750             root = xmlDocGetRootElement(docu->doc);
4751             if (root == NULL) {
4752                 xmlRngPErr(ctxt, node, XML_RNGP_EXTERNALREF_EMTPY,
4753                            "xmlRelaxNGParse: %s is empty\n", ctxt->URL,
4754                            NULL);
4755                 return (NULL);
4756             }
4757             /*
4758              * ns transmission rules
4759              */
4760             ns = xmlGetProp(root, BAD_CAST "ns");
4761             if (ns == NULL) {
4762                 tmp = node;
4763                 while ((tmp != NULL) && (tmp->type == XML_ELEMENT_NODE)) {
4764                     ns = xmlGetProp(tmp, BAD_CAST "ns");
4765                     if (ns != NULL) {
4766                         break;
4767                     }
4768                     tmp = tmp->parent;
4769                 }
4770                 if (ns != NULL) {
4771                     xmlSetProp(root, BAD_CAST "ns", ns);
4772                     newNs = 1;
4773                     xmlFree(ns);
4774                 }
4775             } else {
4776                 xmlFree(ns);
4777             }
4778
4779             /*
4780              * Parsing to get a precompiled schemas.
4781              */
4782             oldflags = ctxt->flags;
4783             ctxt->flags |= XML_RELAXNG_IN_EXTERNALREF;
4784             docu->schema = xmlRelaxNGParseDocument(ctxt, root);
4785             ctxt->flags = oldflags;
4786             if ((docu->schema != NULL) &&
4787                 (docu->schema->topgrammar != NULL)) {
4788                 docu->content = docu->schema->topgrammar->start;
4789                 if (docu->schema->topgrammar->refs)
4790                     xmlRelaxNGParseImportRefs(ctxt, docu->schema->topgrammar);
4791             }
4792
4793             /*
4794              * the externalRef may be reused in a different ns context
4795              */
4796             if (newNs == 1) {
4797                 xmlUnsetProp(root, BAD_CAST "ns");
4798             }
4799         }
4800         def->content = docu->content;
4801     } else {
4802         def = NULL;
4803     }
4804     return (def);
4805 }
4806
4807 /**
4808  * xmlRelaxNGParsePattern:
4809  * @ctxt:  a Relax-NG parser context
4810  * @node:  the pattern node.
4811  *
4812  * parse the content of a RelaxNG pattern node.
4813  *
4814  * Returns the definition pointer or NULL in case of error or if no
4815  *     pattern is generated.
4816  */
4817 static xmlRelaxNGDefinePtr
4818 xmlRelaxNGParsePattern(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4819 {
4820     xmlRelaxNGDefinePtr def = NULL;
4821
4822     if (node == NULL) {
4823         return (NULL);
4824     }
4825     if (IS_RELAXNG(node, "element")) {
4826         def = xmlRelaxNGParseElement(ctxt, node);
4827     } else if (IS_RELAXNG(node, "attribute")) {
4828         def = xmlRelaxNGParseAttribute(ctxt, node);
4829     } else if (IS_RELAXNG(node, "empty")) {
4830         def = xmlRelaxNGNewDefine(ctxt, node);
4831         if (def == NULL)
4832             return (NULL);
4833         def->type = XML_RELAXNG_EMPTY;
4834         if (node->children != NULL) {
4835             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_NOT_EMPTY,
4836                        "empty: had a child node\n", NULL, NULL);
4837         }
4838     } else if (IS_RELAXNG(node, "text")) {
4839         def = xmlRelaxNGNewDefine(ctxt, node);
4840         if (def == NULL)
4841             return (NULL);
4842         def->type = XML_RELAXNG_TEXT;
4843         if (node->children != NULL) {
4844             xmlRngPErr(ctxt, node, XML_RNGP_TEXT_HAS_CHILD,
4845                        "text: had a child node\n", NULL, NULL);
4846         }
4847     } else if (IS_RELAXNG(node, "zeroOrMore")) {
4848         def = xmlRelaxNGNewDefine(ctxt, node);
4849         if (def == NULL)
4850             return (NULL);
4851         def->type = XML_RELAXNG_ZEROORMORE;
4852         if (node->children == NULL) {
4853             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4854                        "Element %s is empty\n", node->name, NULL);
4855         } else {
4856             def->content =
4857                 xmlRelaxNGParsePatterns(ctxt, node->children, 1);
4858         }
4859     } else if (IS_RELAXNG(node, "oneOrMore")) {
4860         def = xmlRelaxNGNewDefine(ctxt, node);
4861         if (def == NULL)
4862             return (NULL);
4863         def->type = XML_RELAXNG_ONEORMORE;
4864         if (node->children == NULL) {
4865             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4866                        "Element %s is empty\n", node->name, NULL);
4867         } else {
4868             def->content =
4869                 xmlRelaxNGParsePatterns(ctxt, node->children, 1);
4870         }
4871     } else if (IS_RELAXNG(node, "optional")) {
4872         def = xmlRelaxNGNewDefine(ctxt, node);
4873         if (def == NULL)
4874             return (NULL);
4875         def->type = XML_RELAXNG_OPTIONAL;
4876         if (node->children == NULL) {
4877             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4878                        "Element %s is empty\n", node->name, NULL);
4879         } else {
4880             def->content =
4881                 xmlRelaxNGParsePatterns(ctxt, node->children, 1);
4882         }
4883     } else if (IS_RELAXNG(node, "choice")) {
4884         def = xmlRelaxNGNewDefine(ctxt, node);
4885         if (def == NULL)
4886             return (NULL);
4887         def->type = XML_RELAXNG_CHOICE;
4888         if (node->children == NULL) {
4889             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4890                        "Element %s is empty\n", node->name, NULL);
4891         } else {
4892             def->content =
4893                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4894         }
4895     } else if (IS_RELAXNG(node, "group")) {
4896         def = xmlRelaxNGNewDefine(ctxt, node);
4897         if (def == NULL)
4898             return (NULL);
4899         def->type = XML_RELAXNG_GROUP;
4900         if (node->children == NULL) {
4901             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4902                        "Element %s is empty\n", node->name, NULL);
4903         } else {
4904             def->content =
4905                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4906         }
4907     } else if (IS_RELAXNG(node, "ref")) {
4908         def = xmlRelaxNGNewDefine(ctxt, node);
4909         if (def == NULL)
4910             return (NULL);
4911         def->type = XML_RELAXNG_REF;
4912         def->name = xmlGetProp(node, BAD_CAST "name");
4913         if (def->name == NULL) {
4914             xmlRngPErr(ctxt, node, XML_RNGP_REF_NO_NAME, "ref has no name\n",
4915                        NULL, NULL);
4916         } else {
4917             xmlRelaxNGNormExtSpace(def->name);
4918             if (xmlValidateNCName(def->name, 0)) {
4919                 xmlRngPErr(ctxt, node, XML_RNGP_REF_NAME_INVALID,
4920                            "ref name '%s' is not an NCName\n", def->name,
4921                            NULL);
4922             }
4923         }
4924         if (node->children != NULL) {
4925             xmlRngPErr(ctxt, node, XML_RNGP_REF_NOT_EMPTY, "ref is not empty\n",
4926                        NULL, NULL);
4927         }
4928         if (ctxt->grammar->refs == NULL)
4929             ctxt->grammar->refs = xmlHashCreate(10);
4930         if (ctxt->grammar->refs == NULL) {
4931             xmlRngPErr(ctxt, node, XML_RNGP_REF_CREATE_FAILED,
4932                        "Could not create references hash\n", NULL, NULL);
4933             def = NULL;
4934         } else {
4935             int tmp;
4936
4937             tmp = xmlHashAddEntry(ctxt->grammar->refs, def->name, def);
4938             if (tmp < 0) {
4939                 xmlRelaxNGDefinePtr prev;
4940
4941                 prev = (xmlRelaxNGDefinePtr)
4942                     xmlHashLookup(ctxt->grammar->refs, def->name);
4943                 if (prev == NULL) {
4944                     if (def->name != NULL) {
4945                         xmlRngPErr(ctxt, node, XML_RNGP_REF_CREATE_FAILED,
4946                                    "Error refs definitions '%s'\n",
4947                                    def->name, NULL);
4948                     } else {
4949                         xmlRngPErr(ctxt, node, XML_RNGP_REF_CREATE_FAILED,
4950                                    "Error refs definitions\n",
4951                                    NULL, NULL);
4952                     }
4953                     def = NULL;
4954                 } else {
4955                     def->nextHash = prev->nextHash;
4956                     prev->nextHash = def;
4957                 }
4958             }
4959         }
4960     } else if (IS_RELAXNG(node, "data")) {
4961         def = xmlRelaxNGParseData(ctxt, node);
4962     } else if (IS_RELAXNG(node, "value")) {
4963         def = xmlRelaxNGParseValue(ctxt, node);
4964     } else if (IS_RELAXNG(node, "list")) {
4965         def = xmlRelaxNGNewDefine(ctxt, node);
4966         if (def == NULL)
4967             return (NULL);
4968         def->type = XML_RELAXNG_LIST;
4969         if (node->children == NULL) {
4970             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4971                        "Element %s is empty\n", node->name, NULL);
4972         } else {
4973             def->content =
4974                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4975         }
4976     } else if (IS_RELAXNG(node, "interleave")) {
4977         def = xmlRelaxNGParseInterleave(ctxt, node);
4978     } else if (IS_RELAXNG(node, "externalRef")) {
4979         def = xmlRelaxNGProcessExternalRef(ctxt, node);
4980     } else if (IS_RELAXNG(node, "notAllowed")) {
4981         def = xmlRelaxNGNewDefine(ctxt, node);
4982         if (def == NULL)
4983             return (NULL);
4984         def->type = XML_RELAXNG_NOT_ALLOWED;
4985         if (node->children != NULL) {
4986             xmlRngPErr(ctxt, node, XML_RNGP_NOTALLOWED_NOT_EMPTY,
4987                        "xmlRelaxNGParse: notAllowed element is not empty\n",
4988                        NULL, NULL);
4989         }
4990     } else if (IS_RELAXNG(node, "grammar")) {
4991         xmlRelaxNGGrammarPtr grammar, old;
4992         xmlRelaxNGGrammarPtr oldparent;
4993
4994 #ifdef DEBUG_GRAMMAR
4995         xmlGenericError(xmlGenericErrorContext,
4996                         "Found <grammar> pattern\n");
4997 #endif
4998
4999         oldparent = ctxt->parentgrammar;
5000         old = ctxt->grammar;
5001         ctxt->parentgrammar = old;
5002         grammar = xmlRelaxNGParseGrammar(ctxt, node->children);
5003         if (old != NULL) {
5004             ctxt->grammar = old;
5005             ctxt->parentgrammar = oldparent;
5006 #if 0
5007             if (grammar != NULL) {
5008                 grammar->next = old->next;
5009                 old->next = grammar;
5010             }
5011 #endif
5012         }
5013         if (grammar != NULL)
5014             def = grammar->start;
5015         else
5016             def = NULL;
5017     } else if (IS_RELAXNG(node, "parentRef")) {
5018         if (ctxt->parentgrammar == NULL) {
5019             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NO_PARENT,
5020                        "Use of parentRef without a parent grammar\n", NULL,
5021                        NULL);
5022             return (NULL);
5023         }
5024         def = xmlRelaxNGNewDefine(ctxt, node);
5025         if (def == NULL)
5026             return (NULL);
5027         def->type = XML_RELAXNG_PARENTREF;
5028         def->name = xmlGetProp(node, BAD_CAST "name");
5029         if (def->name == NULL) {
5030             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NO_NAME,
5031                        "parentRef has no name\n", NULL, NULL);
5032         } else {
5033             xmlRelaxNGNormExtSpace(def->name);
5034             if (xmlValidateNCName(def->name, 0)) {
5035                 xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NAME_INVALID,
5036                            "parentRef name '%s' is not an NCName\n",
5037                            def->name, NULL);
5038             }
5039         }
5040         if (node->children != NULL) {
5041             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NOT_EMPTY,
5042                        "parentRef is not empty\n", NULL, NULL);
5043         }
5044         if (ctxt->parentgrammar->refs == NULL)
5045             ctxt->parentgrammar->refs = xmlHashCreate(10);
5046         if (ctxt->parentgrammar->refs == NULL) {
5047             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_CREATE_FAILED,
5048                        "Could not create references hash\n", NULL, NULL);
5049             def = NULL;
5050         } else if (def->name != NULL) {
5051             int tmp;
5052
5053             tmp =
5054                 xmlHashAddEntry(ctxt->parentgrammar->refs, def->name, def);
5055             if (tmp < 0) {
5056                 xmlRelaxNGDefinePtr prev;
5057
5058                 prev = (xmlRelaxNGDefinePtr)
5059                     xmlHashLookup(ctxt->parentgrammar->refs, def->name);
5060                 if (prev == NULL) {
5061                     xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_CREATE_FAILED,
5062                                "Internal error parentRef definitions '%s'\n",
5063                                def->name, NULL);
5064                     def = NULL;
5065                 } else {
5066                     def->nextHash = prev->nextHash;
5067                     prev->nextHash = def;
5068                 }
5069             }
5070         }
5071     } else if (IS_RELAXNG(node, "mixed")) {
5072         if (node->children == NULL) {
5073             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT, "Mixed is empty\n",
5074                        NULL, NULL);
5075             def = NULL;
5076         } else {
5077             def = xmlRelaxNGParseInterleave(ctxt, node);
5078             if (def != NULL) {
5079                 xmlRelaxNGDefinePtr tmp;
5080
5081                 if ((def->content != NULL) && (def->content->next != NULL)) {
5082                     tmp = xmlRelaxNGNewDefine(ctxt, node);
5083                     if (tmp != NULL) {
5084                         tmp->type = XML_RELAXNG_GROUP;
5085                         tmp->content = def->content;
5086                         def->content = tmp;
5087                     }
5088                 }
5089
5090                 tmp = xmlRelaxNGNewDefine(ctxt, node);
5091                 if (tmp == NULL)
5092                     return (def);
5093                 tmp->type = XML_RELAXNG_TEXT;
5094                 tmp->next = def->content;
5095                 def->content = tmp;
5096             }
5097         }
5098     } else {
5099         xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_CONSTRUCT,
5100                    "Unexpected node %s is not a pattern\n", node->name,
5101                    NULL);
5102         def = NULL;
5103     }
5104     return (def);
5105 }
5106
5107 /**
5108  * xmlRelaxNGParseAttribute:
5109  * @ctxt:  a Relax-NG parser context
5110  * @node:  the element node
5111  *
5112  * parse the content of a RelaxNG attribute node.
5113  *
5114  * Returns the definition pointer or NULL in case of error.
5115  */
5116 static xmlRelaxNGDefinePtr
5117 xmlRelaxNGParseAttribute(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
5118 {
5119     xmlRelaxNGDefinePtr ret, cur;
5120     xmlNodePtr child;
5121     int old_flags;
5122
5123     ret = xmlRelaxNGNewDefine(ctxt, node);
5124     if (ret == NULL)
5125         return (NULL);
5126     ret->type = XML_RELAXNG_ATTRIBUTE;
5127     ret->parent = ctxt->def;
5128     child = node->children;
5129     if (child == NULL) {
5130         xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_EMPTY,
5131                    "xmlRelaxNGParseattribute: attribute has no children\n",
5132                    NULL, NULL);
5133         return (ret);
5134     }
5135     old_flags = ctxt->flags;
5136     ctxt->flags |= XML_RELAXNG_IN_ATTRIBUTE;
5137     cur = xmlRelaxNGParseNameClass(ctxt, child, ret);
5138     if (cur != NULL)
5139         child = child->next;
5140
5141     if (child != NULL) {
5142         cur = xmlRelaxNGParsePattern(ctxt, child);
5143         if (cur != NULL) {
5144             switch (cur->type) {
5145                 case XML_RELAXNG_EMPTY:
5146                 case XML_RELAXNG_NOT_ALLOWED:
5147                 case XML_RELAXNG_TEXT:
5148                 case XML_RELAXNG_ELEMENT:
5149                 case XML_RELAXNG_DATATYPE:
5150                 case XML_RELAXNG_VALUE:
5151                 case XML_RELAXNG_LIST:
5152                 case XML_RELAXNG_REF:
5153                 case XML_RELAXNG_PARENTREF:
5154                 case XML_RELAXNG_EXTERNALREF:
5155                 case XML_RELAXNG_DEF:
5156                 case XML_RELAXNG_ONEORMORE:
5157                 case XML_RELAXNG_ZEROORMORE:
5158                 case XML_RELAXNG_OPTIONAL:
5159                 case XML_RELAXNG_CHOICE:
5160                 case XML_RELAXNG_GROUP:
5161                 case XML_RELAXNG_INTERLEAVE:
5162                 case XML_RELAXNG_ATTRIBUTE:
5163                     ret->content = cur;
5164                     cur->parent = ret;
5165                     break;
5166                 case XML_RELAXNG_START:
5167                 case XML_RELAXNG_PARAM:
5168                 case XML_RELAXNG_EXCEPT:
5169                     xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_CONTENT,
5170                                "attribute has invalid content\n", NULL,
5171                                NULL);
5172                     break;
5173                 case XML_RELAXNG_NOOP:
5174                     xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_NOOP,
5175                                "RNG Internal error, noop found in attribute\n",
5176                                NULL, NULL);
5177                     break;
5178             }
5179         }
5180         child = child->next;
5181     }
5182     if (child != NULL) {
5183         xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_CHILDREN,
5184                    "attribute has multiple children\n", NULL, NULL);
5185     }
5186     ctxt->flags = old_flags;
5187     return (ret);
5188 }
5189
5190 /**
5191  * xmlRelaxNGParseExceptNameClass:
5192  * @ctxt:  a Relax-NG parser context
5193  * @node:  the except node
5194  * @attr:  1 if within an attribute, 0 if within an element
5195  *
5196  * parse the content of a RelaxNG nameClass node.
5197  *
5198  * Returns the definition pointer or NULL in case of error.
5199  */
5200 static xmlRelaxNGDefinePtr
5201 xmlRelaxNGParseExceptNameClass(xmlRelaxNGParserCtxtPtr ctxt,
5202                                xmlNodePtr node, int attr)
5203 {
5204     xmlRelaxNGDefinePtr ret, cur, last = NULL;
5205     xmlNodePtr child;
5206
5207     if (!IS_RELAXNG(node, "except")) {
5208         xmlRngPErr(ctxt, node, XML_RNGP_EXCEPT_MISSING,
5209                    "Expecting an except node\n", NULL, NULL);
5210         return (NULL);
5211     }
5212     if (node->next != NULL) {
5213         xmlRngPErr(ctxt, node, XML_RNGP_EXCEPT_MULTIPLE,
5214                    "exceptNameClass allows only a single except node\n",
5215                    NULL, NULL);
5216     }
5217     if (node->children == NULL) {
5218         xmlRngPErr(ctxt, node, XML_RNGP_EXCEPT_EMPTY, "except has no content\n",
5219                    NULL, NULL);
5220         return (NULL);
5221     }
5222
5223     ret = xmlRelaxNGNewDefine(ctxt, node);
5224     if (ret == NULL)
5225         return (NULL);
5226     ret->type = XML_RELAXNG_EXCEPT;
5227     child = node->children;
5228     while (child != NULL) {
5229         cur = xmlRelaxNGNewDefine(ctxt, child);
5230         if (cur == NULL)
5231             break;
5232         if (attr)
5233             cur->type = XML_RELAXNG_ATTRIBUTE;
5234         else
5235             cur->type = XML_RELAXNG_ELEMENT;
5236
5237         if (xmlRelaxNGParseNameClass(ctxt, child, cur) != NULL) {
5238             if (last == NULL) {
5239                 ret->content = cur;
5240             } else {
5241                 last->next = cur;
5242             }
5243             last = cur;
5244         }
5245         child = child->next;
5246     }
5247
5248     return (ret);
5249 }
5250
5251 /**
5252  * xmlRelaxNGParseNameClass:
5253  * @ctxt:  a Relax-NG parser context
5254  * @node:  the nameClass node
5255  * @def:  the current definition
5256  *
5257  * parse the content of a RelaxNG nameClass node.
5258  *
5259  * Returns the definition pointer or NULL in case of error.
5260  */
5261 static xmlRelaxNGDefinePtr
5262 xmlRelaxNGParseNameClass(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node,
5263                          xmlRelaxNGDefinePtr def)
5264 {
5265     xmlRelaxNGDefinePtr ret, tmp;
5266     xmlChar *val;
5267
5268     ret = def;
5269     if ((IS_RELAXNG(node, "name")) || (IS_RELAXNG(node, "anyName")) ||
5270         (IS_RELAXNG(node, "nsName"))) {
5271         if ((def->type != XML_RELAXNG_ELEMENT) &&
5272             (def->type != XML_RELAXNG_ATTRIBUTE)) {
5273             ret = xmlRelaxNGNewDefine(ctxt, node);
5274             if (ret == NULL)
5275                 return (NULL);
5276             ret->parent = def;
5277             if (ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE)
5278                 ret->type = XML_RELAXNG_ATTRIBUTE;
5279             else
5280                 ret->type = XML_RELAXNG_ELEMENT;
5281         }
5282     }
5283     if (IS_RELAXNG(node, "name")) {
5284         val = xmlNodeGetContent(node);
5285         xmlRelaxNGNormExtSpace(val);
5286         if (xmlValidateNCName(val, 0)) {
5287             if (node->parent != NULL)
5288                 xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_NAME,
5289                            "Element %s name '%s' is not an NCName\n",
5290                            node->parent->name, val);
5291             else
5292                 xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_NAME,
5293                            "name '%s' is not an NCName\n",
5294                            val, NULL);
5295         }
5296         ret->name = val;
5297         val = xmlGetProp(node, BAD_CAST "ns");
5298         ret->ns = val;
5299         if ((ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE) &&
5300             (val != NULL) &&
5301             (xmlStrEqual(val, BAD_CAST "http://www.w3.org/2000/xmlns"))) {
5302             xmlRngPErr(ctxt, node, XML_RNGP_XML_NS,
5303                         "Attribute with namespace '%s' is not allowed\n",
5304                         val, NULL);
5305         }
5306         if ((ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE) &&
5307             (val != NULL) &&
5308             (val[0] == 0) && (xmlStrEqual(ret->name, BAD_CAST "xmlns"))) {
5309             xmlRngPErr(ctxt, node, XML_RNGP_XMLNS_NAME,
5310                        "Attribute with QName 'xmlns' is not allowed\n",
5311                        val, NULL);
5312         }
5313     } else if (IS_RELAXNG(node, "anyName")) {
5314         ret->name = NULL;
5315         ret->ns = NULL;
5316         if (node->children != NULL) {
5317             ret->nameClass =
5318                 xmlRelaxNGParseExceptNameClass(ctxt, node->children,
5319                                                (def->type ==
5320                                                 XML_RELAXNG_ATTRIBUTE));
5321         }
5322     } else if (IS_RELAXNG(node, "nsName")) {
5323         ret->name = NULL;
5324         ret->ns = xmlGetProp(node, BAD_CAST "ns");
5325         if (ret->ns == NULL) {
5326             xmlRngPErr(ctxt, node, XML_RNGP_NSNAME_NO_NS,
5327                        "nsName has no ns attribute\n", NULL, NULL);
5328         }
5329         if ((ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE) &&
5330             (ret->ns != NULL) &&
5331             (xmlStrEqual
5332              (ret->ns, BAD_CAST "http://www.w3.org/2000/xmlns"))) {
5333             xmlRngPErr(ctxt, node, XML_RNGP_XML_NS,
5334                        "Attribute with namespace '%s' is not allowed\n",
5335                        ret->ns, NULL);
5336         }
5337         if (node->children != NULL) {
5338             ret->nameClass =
5339                 xmlRelaxNGParseExceptNameClass(ctxt, node->children,
5340                                                (def->type ==
5341                                                 XML_RELAXNG_ATTRIBUTE));
5342         }
5343     } else if (IS_RELAXNG(node, "choice")) {
5344         xmlNodePtr child;
5345         xmlRelaxNGDefinePtr last = NULL;
5346
5347         ret = xmlRelaxNGNewDefine(ctxt, node);
5348         if (ret == NULL)
5349             return (NULL);
5350         ret->parent = def;
5351         ret->type = XML_RELAXNG_CHOICE;
5352
5353         if (node->children == NULL) {
5354             xmlRngPErr(ctxt, node, XML_RNGP_CHOICE_EMPTY,
5355                        "Element choice is empty\n", NULL, NULL);
5356         } else {
5357
5358             child = node->children;
5359             while (child != NULL) {
5360                 tmp = xmlRelaxNGParseNameClass(ctxt, child, ret);
5361                 if (tmp != NULL) {
5362                     if (last == NULL) {
5363                         last = ret->nameClass = tmp;
5364                     } else {
5365                         last->next = tmp;
5366                         last = tmp;
5367                     }
5368                 }
5369                 child = child->next;
5370             }
5371         }
5372     } else {
5373         xmlRngPErr(ctxt, node, XML_RNGP_CHOICE_CONTENT,
5374                    "expecting name, anyName, nsName or choice : got %s\n",
5375                    (node == NULL ? (const xmlChar *) "nothing" : node->name),
5376                    NULL);
5377         return (NULL);
5378     }
5379     if (ret != def) {
5380         if (def->nameClass == NULL) {
5381             def->nameClass = ret;
5382         } else {
5383             tmp = def->nameClass;
5384             while (tmp->next != NULL) {
5385                 tmp = tmp->next;
5386             }
5387             tmp->next = ret;
5388         }
5389     }
5390     return (ret);
5391 }
5392
5393 /**
5394  * xmlRelaxNGParseElement:
5395  * @ctxt:  a Relax-NG parser context
5396  * @node:  the element node
5397  *
5398  * parse the content of a RelaxNG element node.
5399  *
5400  * Returns the definition pointer or NULL in case of error.
5401  */
5402 static xmlRelaxNGDefinePtr
5403 xmlRelaxNGParseElement(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
5404 {
5405     xmlRelaxNGDefinePtr ret, cur, last;
5406     xmlNodePtr child;
5407     const xmlChar *olddefine;
5408
5409     ret = xmlRelaxNGNewDefine(ctxt, node);
5410     if (ret == NULL)
5411         return (NULL);
5412     ret->type = XML_RELAXNG_ELEMENT;
5413     ret->parent = ctxt->def;
5414     child = node->children;
5415     if (child == NULL) {
5416         xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_EMPTY,
5417                    "xmlRelaxNGParseElement: element has no children\n",
5418                    NULL, NULL);
5419         return (ret);
5420     }
5421     cur = xmlRelaxNGParseNameClass(ctxt, child, ret);
5422     if (cur != NULL)
5423         child = child->next;
5424
5425     if (child == NULL) {
5426         xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_NO_CONTENT,
5427                    "xmlRelaxNGParseElement: element has no content\n",
5428                    NULL, NULL);
5429         return (ret);
5430     }
5431     olddefine = ctxt->define;
5432     ctxt->define = NULL;
5433     last = NULL;
5434     while (child != NULL) {
5435         cur = xmlRelaxNGParsePattern(ctxt, child);
5436         if (cur != NULL) {
5437             cur->parent = ret;
5438             switch (cur->type) {
5439                 case XML_RELAXNG_EMPTY:
5440                 case XML_RELAXNG_NOT_ALLOWED:
5441                 case XML_RELAXNG_TEXT:
5442                 case XML_RELAXNG_ELEMENT:
5443                 case XML_RELAXNG_DATATYPE:
5444                 case XML_RELAXNG_VALUE:
5445                 case XML_RELAXNG_LIST:
5446                 case XML_RELAXNG_REF:
5447                 case XML_RELAXNG_PARENTREF:
5448                 case XML_RELAXNG_EXTERNALREF:
5449                 case XML_RELAXNG_DEF:
5450                 case XML_RELAXNG_ZEROORMORE:
5451                 case XML_RELAXNG_ONEORMORE:
5452                 case XML_RELAXNG_OPTIONAL:
5453                 case XML_RELAXNG_CHOICE:
5454                 case XML_RELAXNG_GROUP:
5455                 case XML_RELAXNG_INTERLEAVE:
5456                     if (last == NULL) {
5457                         ret->content = last = cur;
5458                     } else {
5459                         if ((last->type == XML_RELAXNG_ELEMENT) &&
5460                             (ret->content == last)) {
5461                             ret->content = xmlRelaxNGNewDefine(ctxt, node);
5462                             if (ret->content != NULL) {
5463                                 ret->content->type = XML_RELAXNG_GROUP;
5464                                 ret->content->content = last;
5465                             } else {
5466                                 ret->content = last;
5467                             }
5468                         }
5469                         last->next = cur;
5470                         last = cur;
5471                     }
5472                     break;
5473                 case XML_RELAXNG_ATTRIBUTE:
5474                     cur->next = ret->attrs;
5475                     ret->attrs = cur;
5476                     break;
5477                 case XML_RELAXNG_START:
5478                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5479                                "RNG Internal error, start found in element\n",
5480                                NULL, NULL);
5481                     break;
5482                 case XML_RELAXNG_PARAM:
5483                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5484                                "RNG Internal error, param found in element\n",
5485                                NULL, NULL);
5486                     break;
5487                 case XML_RELAXNG_EXCEPT:
5488                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5489                                "RNG Internal error, except found in element\n",
5490                                NULL, NULL);
5491                     break;
5492                 case XML_RELAXNG_NOOP:
5493                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5494                                "RNG Internal error, noop found in element\n",
5495                                NULL, NULL);
5496                     break;
5497             }
5498         }
5499         child = child->next;
5500     }
5501     ctxt->define = olddefine;
5502     return (ret);
5503 }
5504
5505 /**
5506  * xmlRelaxNGParsePatterns:
5507  * @ctxt:  a Relax-NG parser context
5508  * @nodes:  list of nodes
5509  * @group:  use an implicit <group> for elements
5510  *
5511  * parse the content of a RelaxNG start node.
5512  *
5513  * Returns the definition pointer or NULL in case of error.
5514  */
5515 static xmlRelaxNGDefinePtr
5516 xmlRelaxNGParsePatterns(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes,
5517                         int group)
5518 {
5519     xmlRelaxNGDefinePtr def = NULL, last = NULL, cur, parent;
5520
5521     parent = ctxt->def;
5522     while (nodes != NULL) {
5523         if (IS_RELAXNG(nodes, "element")) {
5524             cur = xmlRelaxNGParseElement(ctxt, nodes);
5525             if (def == NULL) {
5526                 def = last = cur;
5527             } else {
5528                 if ((group == 1) && (def->type == XML_RELAXNG_ELEMENT) &&
5529                     (def == last)) {
5530                     def = xmlRelaxNGNewDefine(ctxt, nodes);
5531                     def->type = XML_RELAXNG_GROUP;
5532                     def->content = last;
5533                 }
5534                 last->next = cur;
5535                 last = cur;
5536             }
5537             cur->parent = parent;
5538         } else {
5539             cur = xmlRelaxNGParsePattern(ctxt, nodes);
5540             if (cur != NULL) {
5541                 if (def == NULL) {
5542                     def = last = cur;
5543                 } else {
5544                     last->next = cur;
5545                     last = cur;
5546                 }
5547             }
5548         }
5549         nodes = nodes->next;
5550     }
5551     return (def);
5552 }
5553
5554 /**
5555  * xmlRelaxNGParseStart:
5556  * @ctxt:  a Relax-NG parser context
5557  * @nodes:  start children nodes
5558  *
5559  * parse the content of a RelaxNG start node.
5560  *
5561  * Returns 0 in case of success, -1 in case of error
5562  */
5563 static int
5564 xmlRelaxNGParseStart(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes)
5565 {
5566     int ret = 0;
5567     xmlRelaxNGDefinePtr def = NULL, last;
5568
5569     if (nodes == NULL) {
5570         xmlRngPErr(ctxt, nodes, XML_RNGP_START_EMPTY, "start has no children\n",
5571                    NULL, NULL);
5572         return (-1);
5573     }
5574     if (IS_RELAXNG(nodes, "empty")) {
5575         def = xmlRelaxNGNewDefine(ctxt, nodes);
5576         if (def == NULL)
5577             return (-1);
5578         def->type = XML_RELAXNG_EMPTY;
5579         if (nodes->children != NULL) {
5580             xmlRngPErr(ctxt, nodes, XML_RNGP_EMPTY_CONTENT,
5581                        "element empty is not empty\n", NULL, NULL);
5582         }
5583     } else if (IS_RELAXNG(nodes, "notAllowed")) {
5584         def = xmlRelaxNGNewDefine(ctxt, nodes);
5585         if (def == NULL)
5586             return (-1);
5587         def->type = XML_RELAXNG_NOT_ALLOWED;
5588         if (nodes->children != NULL) {
5589             xmlRngPErr(ctxt, nodes, XML_RNGP_NOTALLOWED_NOT_EMPTY,
5590                        "element notAllowed is not empty\n", NULL, NULL);
5591         }
5592     } else {
5593         def = xmlRelaxNGParsePatterns(ctxt, nodes, 1);
5594     }
5595     if (ctxt->grammar->start != NULL) {
5596         last = ctxt->grammar->start;
5597         while (last->next != NULL)
5598             last = last->next;
5599         last->next = def;
5600     } else {
5601         ctxt->grammar->start = def;
5602     }
5603     nodes = nodes->next;
5604     if (nodes != NULL) {
5605         xmlRngPErr(ctxt, nodes, XML_RNGP_START_CONTENT,
5606                    "start more than one children\n", NULL, NULL);
5607         return (-1);
5608     }
5609     return (ret);
5610 }
5611
5612 /**
5613  * xmlRelaxNGParseGrammarContent:
5614  * @ctxt:  a Relax-NG parser context
5615  * @nodes:  grammar children nodes
5616  *
5617  * parse the content of a RelaxNG grammar node.
5618  *
5619  * Returns 0 in case of success, -1 in case of error
5620  */
5621 static int
5622 xmlRelaxNGParseGrammarContent(xmlRelaxNGParserCtxtPtr ctxt,
5623                               xmlNodePtr nodes)
5624 {
5625     int ret = 0, tmp;
5626
5627     if (nodes == NULL) {
5628         xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_EMPTY,
5629                    "grammar has no children\n", NULL, NULL);
5630         return (-1);
5631     }
5632     while (nodes != NULL) {
5633         if (IS_RELAXNG(nodes, "start")) {
5634             if (nodes->children == NULL) {
5635                 xmlRngPErr(ctxt, nodes, XML_RNGP_START_EMPTY,
5636                            "start has no children\n", NULL, NULL);
5637             } else {
5638                 tmp = xmlRelaxNGParseStart(ctxt, nodes->children);
5639                 if (tmp != 0)
5640                     ret = -1;
5641             }
5642         } else if (IS_RELAXNG(nodes, "define")) {
5643             tmp = xmlRelaxNGParseDefine(ctxt, nodes);
5644             if (tmp != 0)
5645                 ret = -1;
5646         } else if (IS_RELAXNG(nodes, "include")) {
5647             tmp = xmlRelaxNGParseInclude(ctxt, nodes);
5648             if (tmp != 0)
5649                 ret = -1;
5650         } else {
5651             xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_CONTENT,
5652                        "grammar has unexpected child %s\n", nodes->name,
5653                        NULL);
5654             ret = -1;
5655         }
5656         nodes = nodes->next;
5657     }
5658     return (ret);
5659 }
5660
5661 /**
5662  * xmlRelaxNGCheckReference:
5663  * @ref:  the ref
5664  * @ctxt:  a Relax-NG parser context
5665  * @name:  the name associated to the defines
5666  *
5667  * Applies the 4.17. combine attribute rule for all the define
5668  * element of a given grammar using the same name.
5669  */
5670 static void
5671 xmlRelaxNGCheckReference(xmlRelaxNGDefinePtr ref,
5672                          xmlRelaxNGParserCtxtPtr ctxt,
5673                          const xmlChar * name)
5674 {
5675     xmlRelaxNGGrammarPtr grammar;
5676     xmlRelaxNGDefinePtr def, cur;
5677
5678     /*
5679      * Those rules don't apply to imported ref from xmlRelaxNGParseImportRef
5680      */
5681     if (ref->dflags & IS_EXTERNAL_REF)
5682         return;
5683
5684     grammar = ctxt->grammar;
5685     if (grammar == NULL) {
5686         xmlRngPErr(ctxt, ref->node, XML_ERR_INTERNAL_ERROR,
5687                    "Internal error: no grammar in CheckReference %s\n",
5688                    name, NULL);
5689         return;
5690     }
5691     if (ref->content != NULL) {
5692         xmlRngPErr(ctxt, ref->node, XML_ERR_INTERNAL_ERROR,
5693                    "Internal error: reference has content in CheckReference %s\n",
5694                    name, NULL);
5695         return;
5696     }
5697     if (grammar->defs != NULL) {
5698         def = xmlHashLookup(grammar->defs, name);
5699         if (def != NULL) {
5700             cur = ref;
5701             while (cur != NULL) {
5702                 cur->content = def;
5703                 cur = cur->nextHash;
5704             }
5705         } else {
5706             xmlRngPErr(ctxt, ref->node, XML_RNGP_REF_NO_DEF,
5707                        "Reference %s has no matching definition\n", name,
5708                        NULL);
5709         }
5710     } else {
5711         xmlRngPErr(ctxt, ref->node, XML_RNGP_REF_NO_DEF,
5712                    "Reference %s has no matching definition\n", name,
5713                    NULL);
5714     }
5715 }
5716
5717 /**
5718  * xmlRelaxNGCheckCombine:
5719  * @define:  the define(s) list
5720  * @ctxt:  a Relax-NG parser context
5721  * @name:  the name associated to the defines
5722  *
5723  * Applies the 4.17. combine attribute rule for all the define
5724  * element of a given grammar using the same name.
5725  */
5726 static void
5727 xmlRelaxNGCheckCombine(xmlRelaxNGDefinePtr define,
5728                        xmlRelaxNGParserCtxtPtr ctxt, const xmlChar * name)
5729 {
5730     xmlChar *combine;
5731     int choiceOrInterleave = -1;
5732     int missing = 0;
5733     xmlRelaxNGDefinePtr cur, last, tmp, tmp2;
5734
5735     if (define->nextHash == NULL)
5736         return;
5737     cur = define;
5738     while (cur != NULL) {
5739         combine = xmlGetProp(cur->node, BAD_CAST "combine");
5740         if (combine != NULL) {
5741             if (xmlStrEqual(combine, BAD_CAST "choice")) {
5742                 if (choiceOrInterleave == -1)
5743                     choiceOrInterleave = 1;
5744                 else if (choiceOrInterleave == 0) {
5745                     xmlRngPErr(ctxt, define->node, XML_RNGP_DEF_CHOICE_AND_INTERLEAVE,
5746                                "Defines for %s use both 'choice' and 'interleave'\n",
5747                                name, NULL);
5748                 }
5749             } else if (xmlStrEqual(combine, BAD_CAST "interleave")) {
5750                 if (choiceOrInterleave == -1)
5751                     choiceOrInterleave = 0;
5752                 else if (choiceOrInterleave == 1) {
5753                     xmlRngPErr(ctxt, define->node, XML_RNGP_DEF_CHOICE_AND_INTERLEAVE,
5754                                "Defines for %s use both 'choice' and 'interleave'\n",
5755                                name, NULL);
5756                 }
5757             } else {
5758                 xmlRngPErr(ctxt, define->node, XML_RNGP_UNKNOWN_COMBINE,
5759                            "Defines for %s use unknown combine value '%s''\n",
5760                            name, combine);
5761             }
5762             xmlFree(combine);
5763         } else {
5764             if (missing == 0)
5765                 missing = 1;
5766             else {
5767                 xmlRngPErr(ctxt, define->node, XML_RNGP_NEED_COMBINE,
5768                            "Some defines for %s needs the combine attribute\n",
5769                            name, NULL);
5770             }
5771         }
5772
5773         cur = cur->nextHash;
5774     }
5775 #ifdef DEBUG
5776     xmlGenericError(xmlGenericErrorContext,
5777                     "xmlRelaxNGCheckCombine(): merging %s defines: %d\n",
5778                     name, choiceOrInterleave);
5779 #endif
5780     if (choiceOrInterleave == -1)
5781         choiceOrInterleave = 0;
5782     cur = xmlRelaxNGNewDefine(ctxt, define->node);
5783     if (cur == NULL)
5784         return;
5785     if (choiceOrInterleave == 0)
5786         cur->type = XML_RELAXNG_INTERLEAVE;
5787     else
5788         cur->type = XML_RELAXNG_CHOICE;
5789     tmp = define;
5790     last = NULL;
5791     while (tmp != NULL) {
5792         if (tmp->content != NULL) {
5793             if (tmp->content->next != NULL) {
5794                 /*
5795                  * we need first to create a wrapper.
5796                  */
5797                 tmp2 = xmlRelaxNGNewDefine(ctxt, tmp->content->node);
5798                 if (tmp2 == NULL)
5799                     break;
5800                 tmp2->type = XML_RELAXNG_GROUP;
5801                 tmp2->content = tmp->content;
5802             } else {
5803                 tmp2 = tmp->content;
5804             }
5805             if (last == NULL) {
5806                 cur->content = tmp2;
5807             } else {
5808                 last->next = tmp2;
5809             }
5810             last = tmp2;
5811         }
5812         tmp->content = cur;
5813         tmp = tmp->nextHash;
5814     }
5815     define->content = cur;
5816     if (choiceOrInterleave == 0) {
5817         if (ctxt->interleaves == NULL)
5818             ctxt->interleaves = xmlHashCreate(10);
5819         if (ctxt->interleaves == NULL) {
5820             xmlRngPErr(ctxt, define->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5821                        "Failed to create interleaves hash table\n", NULL,
5822                        NULL);
5823         } else {
5824             char tmpname[32];
5825
5826             snprintf(tmpname, 32, "interleave%d", ctxt->nbInterleaves++);
5827             if (xmlHashAddEntry(ctxt->interleaves, BAD_CAST tmpname, cur) <
5828                 0) {
5829                 xmlRngPErr(ctxt, define->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5830                            "Failed to add %s to hash table\n",
5831                            (const xmlChar *) tmpname, NULL);
5832             }
5833         }
5834     }
5835 }
5836
5837 /**
5838  * xmlRelaxNGCombineStart:
5839  * @ctxt:  a Relax-NG parser context
5840  * @grammar:  the grammar
5841  *
5842  * Applies the 4.17. combine rule for all the start
5843  * element of a given grammar.
5844  */
5845 static void
5846 xmlRelaxNGCombineStart(xmlRelaxNGParserCtxtPtr ctxt,
5847                        xmlRelaxNGGrammarPtr grammar)
5848 {
5849     xmlRelaxNGDefinePtr starts;
5850     xmlChar *combine;
5851     int choiceOrInterleave = -1;
5852     int missing = 0;
5853     xmlRelaxNGDefinePtr cur;
5854
5855     starts = grammar->start;
5856     if ((starts == NULL) || (starts->next == NULL))
5857         return;
5858     cur = starts;
5859     while (cur != NULL) {
5860         if ((cur->node == NULL) || (cur->node->parent == NULL) ||
5861             (!xmlStrEqual(cur->node->parent->name, BAD_CAST "start"))) {
5862             combine = NULL;
5863             xmlRngPErr(ctxt, cur->node, XML_RNGP_START_MISSING,
5864                        "Internal error: start element not found\n", NULL,
5865                        NULL);
5866         } else {
5867             combine = xmlGetProp(cur->node->parent, BAD_CAST "combine");
5868         }
5869
5870         if (combine != NULL) {
5871             if (xmlStrEqual(combine, BAD_CAST "choice")) {
5872                 if (choiceOrInterleave == -1)
5873                     choiceOrInterleave = 1;
5874                 else if (choiceOrInterleave == 0) {
5875                     xmlRngPErr(ctxt, cur->node, XML_RNGP_START_CHOICE_AND_INTERLEAVE,
5876                                "<start> use both 'choice' and 'interleave'\n",
5877                                NULL, NULL);
5878                 }
5879             } else if (xmlStrEqual(combine, BAD_CAST "interleave")) {
5880                 if (choiceOrInterleave == -1)
5881                     choiceOrInterleave = 0;
5882                 else if (choiceOrInterleave == 1) {
5883                     xmlRngPErr(ctxt, cur->node, XML_RNGP_START_CHOICE_AND_INTERLEAVE,
5884                                "<start> use both 'choice' and 'interleave'\n",
5885                                NULL, NULL);
5886                 }
5887             } else {
5888                 xmlRngPErr(ctxt, cur->node, XML_RNGP_UNKNOWN_COMBINE,
5889                            "<start> uses unknown combine value '%s''\n",
5890                            combine, NULL);
5891             }
5892             xmlFree(combine);
5893         } else {
5894             if (missing == 0)
5895                 missing = 1;
5896             else {
5897                 xmlRngPErr(ctxt, cur->node, XML_RNGP_NEED_COMBINE,
5898                            "Some <start> element miss the combine attribute\n",
5899                            NULL, NULL);
5900             }
5901         }
5902
5903         cur = cur->next;
5904     }
5905 #ifdef DEBUG
5906     xmlGenericError(xmlGenericErrorContext,
5907                     "xmlRelaxNGCombineStart(): merging <start>: %d\n",
5908                     choiceOrInterleave);
5909 #endif
5910     if (choiceOrInterleave == -1)
5911         choiceOrInterleave = 0;
5912     cur = xmlRelaxNGNewDefine(ctxt, starts->node);
5913     if (cur == NULL)
5914         return;
5915     if (choiceOrInterleave == 0)
5916         cur->type = XML_RELAXNG_INTERLEAVE;
5917     else
5918         cur->type = XML_RELAXNG_CHOICE;
5919     cur->content = grammar->start;
5920     grammar->start = cur;
5921     if (choiceOrInterleave == 0) {
5922         if (ctxt->interleaves == NULL)
5923             ctxt->interleaves = xmlHashCreate(10);
5924         if (ctxt->interleaves == NULL) {
5925             xmlRngPErr(ctxt, cur->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5926                        "Failed to create interleaves hash table\n", NULL,
5927                        NULL);
5928         } else {
5929             char tmpname[32];
5930
5931             snprintf(tmpname, 32, "interleave%d", ctxt->nbInterleaves++);
5932             if (xmlHashAddEntry(ctxt->interleaves, BAD_CAST tmpname, cur) <
5933                 0) {
5934                 xmlRngPErr(ctxt, cur->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5935                            "Failed to add %s to hash table\n",
5936                            (const xmlChar *) tmpname, NULL);
5937             }
5938         }
5939     }
5940 }
5941
5942 /**
5943  * xmlRelaxNGCheckCycles:
5944  * @ctxt:  a Relax-NG parser context
5945  * @nodes:  grammar children nodes
5946  * @depth:  the counter
5947  *
5948  * Check for cycles.
5949  *
5950  * Returns 0 if check passed, and -1 in case of error
5951  */
5952 static int
5953 xmlRelaxNGCheckCycles(xmlRelaxNGParserCtxtPtr ctxt,
5954                       xmlRelaxNGDefinePtr cur, int depth)
5955 {
5956     int ret = 0;
5957
5958     while ((ret == 0) && (cur != NULL)) {
5959         if ((cur->type == XML_RELAXNG_REF) ||
5960             (cur->type == XML_RELAXNG_PARENTREF)) {
5961             if (cur->depth == -1) {
5962                 cur->depth = depth;
5963                 ret = xmlRelaxNGCheckCycles(ctxt, cur->content, depth);
5964                 cur->depth = -2;
5965             } else if (depth == cur->depth) {
5966                 xmlRngPErr(ctxt, cur->node, XML_RNGP_REF_CYCLE,
5967                            "Detected a cycle in %s references\n",
5968                            cur->name, NULL);
5969                 return (-1);
5970             }
5971         } else if (cur->type == XML_RELAXNG_ELEMENT) {
5972             ret = xmlRelaxNGCheckCycles(ctxt, cur->content, depth + 1);
5973         } else {
5974             ret = xmlRelaxNGCheckCycles(ctxt, cur->content, depth);
5975         }
5976         cur = cur->next;
5977     }
5978     return (ret);
5979 }
5980
5981 /**
5982  * xmlRelaxNGTryUnlink:
5983  * @ctxt:  a Relax-NG parser context
5984  * @cur:  the definition to unlink
5985  * @parent:  the parent definition
5986  * @prev:  the previous sibling definition
5987  *
5988  * Try to unlink a definition. If not possble make it a NOOP
5989  *
5990  * Returns the new prev definition
5991  */
5992 static xmlRelaxNGDefinePtr
5993 xmlRelaxNGTryUnlink(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,
5994                     xmlRelaxNGDefinePtr cur,
5995                     xmlRelaxNGDefinePtr parent, xmlRelaxNGDefinePtr prev)
5996 {
5997     if (prev != NULL) {
5998         prev->next = cur->next;
5999     } else {
6000         if (parent != NULL) {
6001             if (parent->content == cur)
6002                 parent->content = cur->next;
6003             else if (parent->attrs == cur)
6004                 parent->attrs = cur->next;
6005             else if (parent->nameClass == cur)
6006                 parent->nameClass = cur->next;
6007         } else {
6008             cur->type = XML_RELAXNG_NOOP;
6009             prev = cur;
6010         }
6011     }
6012     return (prev);
6013 }
6014
6015 /**
6016  * xmlRelaxNGSimplify:
6017  * @ctxt:  a Relax-NG parser context
6018  * @nodes:  grammar children nodes
6019  *
6020  * Check for simplification of empty and notAllowed
6021  */
6022 static void
6023 xmlRelaxNGSimplify(xmlRelaxNGParserCtxtPtr ctxt,
6024                    xmlRelaxNGDefinePtr cur, xmlRelaxNGDefinePtr parent)
6025 {
6026     xmlRelaxNGDefinePtr prev = NULL;
6027
6028     while (cur != NULL) {
6029         if ((cur->type == XML_RELAXNG_REF) ||
6030             (cur->type == XML_RELAXNG_PARENTREF)) {
6031             if (cur->depth != -3) {
6032                 cur->depth = -3;
6033                 xmlRelaxNGSimplify(ctxt, cur->content, cur);
6034             }
6035         } else if (cur->type == XML_RELAXNG_NOT_ALLOWED) {
6036             cur->parent = parent;
6037             if ((parent != NULL) &&
6038                 ((parent->type == XML_RELAXNG_ATTRIBUTE) ||
6039                  (parent->type == XML_RELAXNG_LIST) ||
6040                  (parent->type == XML_RELAXNG_GROUP) ||
6041                  (parent->type == XML_RELAXNG_INTERLEAVE) ||
6042                  (parent->type == XML_RELAXNG_ONEORMORE) ||
6043                  (parent->type == XML_RELAXNG_ZEROORMORE))) {
6044                 parent->type = XML_RELAXNG_NOT_ALLOWED;
6045                 break;
6046             }
6047             if ((parent != NULL) && (parent->type == XML_RELAXNG_CHOICE)) {
6048                 prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6049             } else
6050                 prev = cur;
6051         } else if (cur->type == XML_RELAXNG_EMPTY) {
6052             cur->parent = parent;
6053             if ((parent != NULL) &&
6054                 ((parent->type == XML_RELAXNG_ONEORMORE) ||
6055                  (parent->type == XML_RELAXNG_ZEROORMORE))) {
6056                 parent->type = XML_RELAXNG_EMPTY;
6057                 break;
6058             }
6059             if ((parent != NULL) &&
6060                 ((parent->type == XML_RELAXNG_GROUP) ||
6061                  (parent->type == XML_RELAXNG_INTERLEAVE))) {
6062                 prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6063             } else
6064                 prev = cur;
6065         } else {
6066             cur->parent = parent;
6067             if (cur->content != NULL)
6068                 xmlRelaxNGSimplify(ctxt, cur->content, cur);
6069             if ((cur->type != XML_RELAXNG_VALUE) && (cur->attrs != NULL))
6070                 xmlRelaxNGSimplify(ctxt, cur->attrs, cur);
6071             if (cur->nameClass != NULL)
6072                 xmlRelaxNGSimplify(ctxt, cur->nameClass, cur);
6073             /*
6074              * On Elements, try to move attribute only generating rules on
6075              * the attrs rules.
6076              */
6077             if (cur->type == XML_RELAXNG_ELEMENT) {
6078                 int attronly;
6079                 xmlRelaxNGDefinePtr tmp, pre;
6080
6081                 while (cur->content != NULL) {
6082                     attronly =
6083                         xmlRelaxNGGenerateAttributes(ctxt, cur->content);
6084                     if (attronly == 1) {
6085                         /*
6086                          * migrate cur->content to attrs
6087                          */
6088                         tmp = cur->content;
6089                         cur->content = tmp->next;
6090                         tmp->next = cur->attrs;
6091                         cur->attrs = tmp;
6092                     } else {
6093                         /*
6094                          * cur->content can generate elements or text
6095                          */
6096                         break;
6097                     }
6098                 }
6099                 pre = cur->content;
6100                 while ((pre != NULL) && (pre->next != NULL)) {
6101                     tmp = pre->next;
6102                     attronly = xmlRelaxNGGenerateAttributes(ctxt, tmp);
6103                     if (attronly == 1) {
6104                         /*
6105                          * migrate tmp to attrs
6106                          */
6107                         pre->next = tmp->next;
6108                         tmp->next = cur->attrs;
6109                         cur->attrs = tmp;
6110                     } else {
6111                         pre = tmp;
6112                     }
6113                 }
6114             }
6115             /*
6116              * This may result in a simplification
6117              */
6118             if ((cur->type == XML_RELAXNG_GROUP) ||
6119                 (cur->type == XML_RELAXNG_INTERLEAVE)) {
6120                 if (cur->content == NULL)
6121                     cur->type = XML_RELAXNG_EMPTY;
6122                 else if (cur->content->next == NULL) {
6123                     if ((parent == NULL) && (prev == NULL)) {
6124                         cur->type = XML_RELAXNG_NOOP;
6125                     } else if (prev == NULL) {
6126                         parent->content = cur->content;
6127                         cur->content->next = cur->next;
6128                         cur = cur->content;
6129                     } else {
6130                         cur->content->next = cur->next;
6131                         prev->next = cur->content;
6132                         cur = cur->content;
6133                     }
6134                 }
6135             }
6136             /*
6137              * the current node may have been transformed back
6138              */
6139             if ((cur->type == XML_RELAXNG_EXCEPT) &&
6140                 (cur->content != NULL) &&
6141                 (cur->content->type == XML_RELAXNG_NOT_ALLOWED)) {
6142                 prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6143             } else if (cur->type == XML_RELAXNG_NOT_ALLOWED) {
6144                 if ((parent != NULL) &&
6145                     ((parent->type == XML_RELAXNG_ATTRIBUTE) ||
6146                      (parent->type == XML_RELAXNG_LIST) ||
6147                      (parent->type == XML_RELAXNG_GROUP) ||
6148                      (parent->type == XML_RELAXNG_INTERLEAVE) ||
6149                      (parent->type == XML_RELAXNG_ONEORMORE) ||
6150                      (parent->type == XML_RELAXNG_ZEROORMORE))) {
6151                     parent->type = XML_RELAXNG_NOT_ALLOWED;
6152                     break;
6153                 }
6154                 if ((parent != NULL) &&
6155                     (parent->type == XML_RELAXNG_CHOICE)) {
6156                     prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6157                 } else
6158                     prev = cur;
6159             } else if (cur->type == XML_RELAXNG_EMPTY) {
6160                 if ((parent != NULL) &&
6161                     ((parent->type == XML_RELAXNG_ONEORMORE) ||
6162                      (parent->type == XML_RELAXNG_ZEROORMORE))) {
6163                     parent->type = XML_RELAXNG_EMPTY;
6164                     break;
6165                 }
6166                 if ((parent != NULL) &&
6167                     ((parent->type == XML_RELAXNG_GROUP) ||
6168                      (parent->type == XML_RELAXNG_INTERLEAVE) ||
6169                      (parent->type == XML_RELAXNG_CHOICE))) {
6170                     prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6171                 } else
6172                     prev = cur;
6173             } else {
6174                 prev = cur;
6175             }
6176         }
6177         cur = cur->next;
6178     }
6179 }
6180
6181 /**
6182  * xmlRelaxNGGroupContentType:
6183  * @ct1:  the first content type
6184  * @ct2:  the second content type
6185  *
6186  * Try to group 2 content types
6187  *
6188  * Returns the content type
6189  */
6190 static xmlRelaxNGContentType
6191 xmlRelaxNGGroupContentType(xmlRelaxNGContentType ct1,
6192                            xmlRelaxNGContentType ct2)
6193 {
6194     if ((ct1 == XML_RELAXNG_CONTENT_ERROR) ||
6195         (ct2 == XML_RELAXNG_CONTENT_ERROR))
6196         return (XML_RELAXNG_CONTENT_ERROR);
6197     if (ct1 == XML_RELAXNG_CONTENT_EMPTY)
6198         return (ct2);
6199     if (ct2 == XML_RELAXNG_CONTENT_EMPTY)
6200         return (ct1);
6201     if ((ct1 == XML_RELAXNG_CONTENT_COMPLEX) &&
6202         (ct2 == XML_RELAXNG_CONTENT_COMPLEX))
6203         return (XML_RELAXNG_CONTENT_COMPLEX);
6204     return (XML_RELAXNG_CONTENT_ERROR);
6205 }
6206
6207 /**
6208  * xmlRelaxNGMaxContentType:
6209  * @ct1:  the first content type
6210  * @ct2:  the second content type
6211  *
6212  * Compute the max content-type
6213  *
6214  * Returns the content type
6215  */
6216 static xmlRelaxNGContentType
6217 xmlRelaxNGMaxContentType(xmlRelaxNGContentType ct1,
6218                          xmlRelaxNGContentType ct2)
6219 {
6220     if ((ct1 == XML_RELAXNG_CONTENT_ERROR) ||
6221         (ct2 == XML_RELAXNG_CONTENT_ERROR))
6222         return (XML_RELAXNG_CONTENT_ERROR);
6223     if ((ct1 == XML_RELAXNG_CONTENT_SIMPLE) ||
6224         (ct2 == XML_RELAXNG_CONTENT_SIMPLE))
6225         return (XML_RELAXNG_CONTENT_SIMPLE);
6226     if ((ct1 == XML_RELAXNG_CONTENT_COMPLEX) ||
6227         (ct2 == XML_RELAXNG_CONTENT_COMPLEX))
6228         return (XML_RELAXNG_CONTENT_COMPLEX);
6229     return (XML_RELAXNG_CONTENT_EMPTY);
6230 }
6231
6232 /**
6233  * xmlRelaxNGCheckRules:
6234  * @ctxt:  a Relax-NG parser context
6235  * @cur:  the current definition
6236  * @flags:  some accumulated flags
6237  * @ptype:  the parent type
6238  *
6239  * Check for rules in section 7.1 and 7.2
6240  *
6241  * Returns the content type of @cur
6242  */
6243 static xmlRelaxNGContentType
6244 xmlRelaxNGCheckRules(xmlRelaxNGParserCtxtPtr ctxt,
6245                      xmlRelaxNGDefinePtr cur, int flags,
6246                      xmlRelaxNGType ptype)
6247 {
6248     int nflags;
6249     xmlRelaxNGContentType ret, tmp, val = XML_RELAXNG_CONTENT_EMPTY;
6250
6251     while (cur != NULL) {
6252         ret = XML_RELAXNG_CONTENT_EMPTY;
6253         if ((cur->type == XML_RELAXNG_REF) ||
6254             (cur->type == XML_RELAXNG_PARENTREF)) {
6255            /*
6256             * This should actually be caught by list//element(ref) at the
6257             * element boundaries, c.f. Bug #159968 local refs are dropped
6258             * in step 4.19.
6259             */
6260 #if 0
6261             if (flags & XML_RELAXNG_IN_LIST) {
6262                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_REF,
6263                            "Found forbidden pattern list//ref\n", NULL,
6264                            NULL);
6265             }
6266 #endif
6267             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6268                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_REF,
6269                            "Found forbidden pattern data/except//ref\n",
6270                            NULL, NULL);
6271             }
6272             if (cur->content == NULL) {
6273                 if (cur->type == XML_RELAXNG_PARENTREF)
6274                     xmlRngPErr(ctxt, cur->node, XML_RNGP_REF_NO_DEF,
6275                                "Internal found no define for parent refs\n",
6276                                NULL, NULL);
6277                 else
6278                     xmlRngPErr(ctxt, cur->node, XML_RNGP_REF_NO_DEF,
6279                                "Internal found no define for ref %s\n",
6280                                (cur->name ? cur->name: BAD_CAST "null"), NULL);
6281             }
6282             if (cur->depth > -4) {
6283                 cur->depth = -4;
6284                 ret = xmlRelaxNGCheckRules(ctxt, cur->content,
6285                                            flags, cur->type);
6286                 cur->depth = ret - 15;
6287             } else if (cur->depth == -4) {
6288                 ret = XML_RELAXNG_CONTENT_COMPLEX;
6289             } else {
6290                 ret = (xmlRelaxNGContentType) (cur->depth + 15);
6291             }
6292         } else if (cur->type == XML_RELAXNG_ELEMENT) {
6293             /*
6294              * The 7.3 Attribute derivation rule for groups is plugged there
6295              */
6296             xmlRelaxNGCheckGroupAttrs(ctxt, cur);
6297             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6298                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_ELEM,
6299                            "Found forbidden pattern data/except//element(ref)\n",
6300                            NULL, NULL);
6301             }
6302             if (flags & XML_RELAXNG_IN_LIST) {
6303                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_ELEM,
6304                            "Found forbidden pattern list//element(ref)\n",
6305                            NULL, NULL);
6306             }
6307             if (flags & XML_RELAXNG_IN_ATTRIBUTE) {
6308                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ATTR_ELEM,
6309                            "Found forbidden pattern attribute//element(ref)\n",
6310                            NULL, NULL);
6311             }
6312             if (flags & XML_RELAXNG_IN_ATTRIBUTE) {
6313                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ATTR_ELEM,
6314                            "Found forbidden pattern attribute//element(ref)\n",
6315                            NULL, NULL);
6316             }
6317             /*
6318              * reset since in the simple form elements are only child
6319              * of grammar/define
6320              */
6321             nflags = 0;
6322             ret =
6323                 xmlRelaxNGCheckRules(ctxt, cur->attrs, nflags, cur->type);
6324             if (ret != XML_RELAXNG_CONTENT_EMPTY) {
6325                 xmlRngPErr(ctxt, cur->node, XML_RNGP_ELEM_CONTENT_EMPTY,
6326                            "Element %s attributes have a content type error\n",
6327                            cur->name, NULL);
6328             }
6329             ret =
6330                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6331                                      cur->type);
6332             if (ret == XML_RELAXNG_CONTENT_ERROR) {
6333                 xmlRngPErr(ctxt, cur->node, XML_RNGP_ELEM_CONTENT_ERROR,
6334                            "Element %s has a content type error\n",
6335                            cur->name, NULL);
6336             } else {
6337                 ret = XML_RELAXNG_CONTENT_COMPLEX;
6338             }
6339         } else if (cur->type == XML_RELAXNG_ATTRIBUTE) {
6340             if (flags & XML_RELAXNG_IN_ATTRIBUTE) {
6341                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ATTR_ATTR,
6342                            "Found forbidden pattern attribute//attribute\n",
6343                            NULL, NULL);
6344             }
6345             if (flags & XML_RELAXNG_IN_LIST) {
6346                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_ATTR,
6347                            "Found forbidden pattern list//attribute\n",
6348                            NULL, NULL);
6349             }
6350             if (flags & XML_RELAXNG_IN_OOMGROUP) {
6351                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ONEMORE_GROUP_ATTR,
6352                            "Found forbidden pattern oneOrMore//group//attribute\n",
6353                            NULL, NULL);
6354             }
6355             if (flags & XML_RELAXNG_IN_OOMINTERLEAVE) {
6356                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR,
6357                            "Found forbidden pattern oneOrMore//interleave//attribute\n",
6358                            NULL, NULL);
6359             }
6360             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6361                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_ATTR,
6362                            "Found forbidden pattern data/except//attribute\n",
6363                            NULL, NULL);
6364             }
6365             if (flags & XML_RELAXNG_IN_START) {
6366                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_ATTR,
6367                            "Found forbidden pattern start//attribute\n",
6368                            NULL, NULL);
6369             }
6370             if ((!(flags & XML_RELAXNG_IN_ONEORMORE))
6371                 && (cur->name == NULL)) {
6372                 if (cur->ns == NULL) {
6373                     xmlRngPErr(ctxt, cur->node, XML_RNGP_ANYNAME_ATTR_ANCESTOR,
6374                                "Found anyName attribute without oneOrMore ancestor\n",
6375                                NULL, NULL);
6376                 } else {
6377                     xmlRngPErr(ctxt, cur->node, XML_RNGP_NSNAME_ATTR_ANCESTOR,
6378                                "Found nsName attribute without oneOrMore ancestor\n",
6379                                NULL, NULL);
6380                 }
6381             }
6382             nflags = flags | XML_RELAXNG_IN_ATTRIBUTE;
6383             xmlRelaxNGCheckRules(ctxt, cur->content, nflags, cur->type);
6384             ret = XML_RELAXNG_CONTENT_EMPTY;
6385         } else if ((cur->type == XML_RELAXNG_ONEORMORE) ||
6386                    (cur->type == XML_RELAXNG_ZEROORMORE)) {
6387             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6388                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_ONEMORE,
6389                            "Found forbidden pattern data/except//oneOrMore\n",
6390                            NULL, NULL);
6391             }
6392             if (flags & XML_RELAXNG_IN_START) {
6393                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_ONEMORE,
6394                            "Found forbidden pattern start//oneOrMore\n",
6395                            NULL, NULL);
6396             }
6397             nflags = flags | XML_RELAXNG_IN_ONEORMORE;
6398             ret =
6399                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6400                                      cur->type);
6401             ret = xmlRelaxNGGroupContentType(ret, ret);
6402         } else if (cur->type == XML_RELAXNG_LIST) {
6403             if (flags & XML_RELAXNG_IN_LIST) {
6404                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_LIST,
6405                            "Found forbidden pattern list//list\n", NULL,
6406                            NULL);
6407             }
6408             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6409                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_LIST,
6410                            "Found forbidden pattern data/except//list\n",
6411                            NULL, NULL);
6412             }
6413             if (flags & XML_RELAXNG_IN_START) {
6414                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_LIST,
6415                            "Found forbidden pattern start//list\n", NULL,
6416                            NULL);
6417             }
6418             nflags = flags | XML_RELAXNG_IN_LIST;
6419             ret =
6420                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6421                                      cur->type);
6422         } else if (cur->type == XML_RELAXNG_GROUP) {
6423             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6424                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_GROUP,
6425                            "Found forbidden pattern data/except//group\n",
6426                            NULL, NULL);
6427             }
6428             if (flags & XML_RELAXNG_IN_START) {
6429                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_GROUP,
6430                            "Found forbidden pattern start//group\n", NULL,
6431                            NULL);
6432             }
6433             if (flags & XML_RELAXNG_IN_ONEORMORE)
6434                 nflags = flags | XML_RELAXNG_IN_OOMGROUP;
6435             else
6436                 nflags = flags;
6437             ret =
6438                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6439                                      cur->type);
6440             /*
6441              * The 7.3 Attribute derivation rule for groups is plugged there
6442              */
6443             xmlRelaxNGCheckGroupAttrs(ctxt, cur);
6444         } else if (cur->type == XML_RELAXNG_INTERLEAVE) {
6445             if (flags & XML_RELAXNG_IN_LIST) {
6446                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_INTERLEAVE,
6447                            "Found forbidden pattern list//interleave\n",
6448                            NULL, NULL);
6449             }
6450             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6451                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE,
6452                            "Found forbidden pattern data/except//interleave\n",
6453                            NULL, NULL);
6454             }
6455             if (flags & XML_RELAXNG_IN_START) {
6456                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE,
6457                            "Found forbidden pattern start//interleave\n",
6458                            NULL, NULL);
6459             }
6460             if (flags & XML_RELAXNG_IN_ONEORMORE)
6461                 nflags = flags | XML_RELAXNG_IN_OOMINTERLEAVE;
6462             else
6463                 nflags = flags;
6464             ret =
6465                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6466                                      cur->type);
6467         } else if (cur->type == XML_RELAXNG_EXCEPT) {
6468             if ((cur->parent != NULL) &&
6469                 (cur->parent->type == XML_RELAXNG_DATATYPE))
6470                 nflags = flags | XML_RELAXNG_IN_DATAEXCEPT;
6471             else
6472                 nflags = flags;
6473             ret =
6474                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6475                                      cur->type);
6476         } else if (cur->type == XML_RELAXNG_DATATYPE) {
6477             if (flags & XML_RELAXNG_IN_START) {
6478                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_DATA,
6479                            "Found forbidden pattern start//data\n", NULL,
6480                            NULL);
6481             }
6482             xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6483             ret = XML_RELAXNG_CONTENT_SIMPLE;
6484         } else if (cur->type == XML_RELAXNG_VALUE) {
6485             if (flags & XML_RELAXNG_IN_START) {
6486                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_VALUE,
6487                            "Found forbidden pattern start//value\n", NULL,
6488                            NULL);
6489             }
6490             xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6491             ret = XML_RELAXNG_CONTENT_SIMPLE;
6492         } else if (cur->type == XML_RELAXNG_TEXT) {
6493             if (flags & XML_RELAXNG_IN_LIST) {
6494                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_TEXT,
6495                            "Found forbidden pattern list//text\n", NULL,
6496                            NULL);
6497             }
6498             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6499                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_TEXT,
6500                            "Found forbidden pattern data/except//text\n",
6501                            NULL, NULL);
6502             }
6503             if (flags & XML_RELAXNG_IN_START) {
6504                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_TEXT,
6505                            "Found forbidden pattern start//text\n", NULL,
6506                            NULL);
6507             }
6508             ret = XML_RELAXNG_CONTENT_COMPLEX;
6509         } else if (cur->type == XML_RELAXNG_EMPTY) {
6510             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6511                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_EMPTY,
6512                            "Found forbidden pattern data/except//empty\n",
6513                            NULL, NULL);
6514             }
6515             if (flags & XML_RELAXNG_IN_START) {
6516                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_EMPTY,
6517                            "Found forbidden pattern start//empty\n", NULL,
6518                            NULL);
6519             }
6520             ret = XML_RELAXNG_CONTENT_EMPTY;
6521         } else if (cur->type == XML_RELAXNG_CHOICE) {
6522             xmlRelaxNGCheckChoiceDeterminism(ctxt, cur);
6523             ret =
6524                 xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6525         } else {
6526             ret =
6527                 xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6528         }
6529         cur = cur->next;
6530         if (ptype == XML_RELAXNG_GROUP) {
6531             val = xmlRelaxNGGroupContentType(val, ret);
6532         } else if (ptype == XML_RELAXNG_INTERLEAVE) {
6533             /*
6534              * TODO: scan complain that tmp is never used, seems on purpose
6535              *       need double-checking
6536              */
6537             tmp = xmlRelaxNGGroupContentType(val, ret);
6538             if (tmp != XML_RELAXNG_CONTENT_ERROR)
6539                 tmp = xmlRelaxNGMaxContentType(val, ret);
6540         } else if (ptype == XML_RELAXNG_CHOICE) {
6541             val = xmlRelaxNGMaxContentType(val, ret);
6542         } else if (ptype == XML_RELAXNG_LIST) {
6543             val = XML_RELAXNG_CONTENT_SIMPLE;
6544         } else if (ptype == XML_RELAXNG_EXCEPT) {
6545             if (ret == XML_RELAXNG_CONTENT_ERROR)
6546                 val = XML_RELAXNG_CONTENT_ERROR;
6547             else
6548                 val = XML_RELAXNG_CONTENT_SIMPLE;
6549         } else {
6550             val = xmlRelaxNGGroupContentType(val, ret);
6551         }
6552
6553     }
6554     return (val);
6555 }
6556
6557 /**
6558  * xmlRelaxNGParseGrammar:
6559  * @ctxt:  a Relax-NG parser context
6560  * @nodes:  grammar children nodes
6561  *
6562  * parse a Relax-NG <grammar> node
6563  *
6564  * Returns the internal xmlRelaxNGGrammarPtr built or
6565  *         NULL in case of error
6566  */
6567 static xmlRelaxNGGrammarPtr
6568 xmlRelaxNGParseGrammar(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes)
6569 {
6570     xmlRelaxNGGrammarPtr ret, tmp, old;
6571
6572 #ifdef DEBUG_GRAMMAR
6573     xmlGenericError(xmlGenericErrorContext, "Parsing a new grammar\n");
6574 #endif
6575
6576     ret = xmlRelaxNGNewGrammar(ctxt);
6577     if (ret == NULL)
6578         return (NULL);
6579
6580     /*
6581      * Link the new grammar in the tree
6582      */
6583     ret->parent = ctxt->grammar;
6584     if (ctxt->grammar != NULL) {
6585         tmp = ctxt->grammar->children;
6586         if (tmp == NULL) {
6587             ctxt->grammar->children = ret;
6588         } else {
6589             while (tmp->next != NULL)
6590                 tmp = tmp->next;
6591             tmp->next = ret;
6592         }
6593     }
6594
6595     old = ctxt->grammar;
6596     ctxt->grammar = ret;
6597     xmlRelaxNGParseGrammarContent(ctxt, nodes);
6598     ctxt->grammar = ret;
6599     if (ctxt->grammar == NULL) {
6600         xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_CONTENT,
6601                    "Failed to parse <grammar> content\n", NULL, NULL);
6602     } else if (ctxt->grammar->start == NULL) {
6603         xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_NO_START,
6604                    "Element <grammar> has no <start>\n", NULL, NULL);
6605     }
6606
6607     /*
6608      * Apply 4.17 merging rules to defines and starts
6609      */
6610     xmlRelaxNGCombineStart(ctxt, ret);
6611     if (ret->defs != NULL) {
6612         xmlHashScan(ret->defs, (xmlHashScanner) xmlRelaxNGCheckCombine,
6613                     ctxt);
6614     }
6615
6616     /*
6617      * link together defines and refs in this grammar
6618      */
6619     if (ret->refs != NULL) {
6620         xmlHashScan(ret->refs, (xmlHashScanner) xmlRelaxNGCheckReference,
6621                     ctxt);
6622     }
6623
6624
6625     /* @@@@ */
6626
6627     ctxt->grammar = old;
6628     return (ret);
6629 }
6630
6631 /**
6632  * xmlRelaxNGParseDocument:
6633  * @ctxt:  a Relax-NG parser context
6634  * @node:  the root node of the RelaxNG schema
6635  *
6636  * parse a Relax-NG definition resource and build an internal
6637  * xmlRelaxNG struture which can be used to validate instances.
6638  *
6639  * Returns the internal XML RelaxNG structure built or
6640  *         NULL in case of error
6641  */
6642 static xmlRelaxNGPtr
6643 xmlRelaxNGParseDocument(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
6644 {
6645     xmlRelaxNGPtr schema = NULL;
6646     const xmlChar *olddefine;
6647     xmlRelaxNGGrammarPtr old;
6648
6649     if ((ctxt == NULL) || (node == NULL))
6650         return (NULL);
6651
6652     schema = xmlRelaxNGNewRelaxNG(ctxt);
6653     if (schema == NULL)
6654         return (NULL);
6655
6656     olddefine = ctxt->define;
6657     ctxt->define = NULL;
6658     if (IS_RELAXNG(node, "grammar")) {
6659         schema->topgrammar = xmlRelaxNGParseGrammar(ctxt, node->children);
6660         if (schema->topgrammar == NULL) {
6661             xmlRelaxNGFree(schema);
6662             return (NULL);
6663         }
6664     } else {
6665         xmlRelaxNGGrammarPtr tmp, ret;
6666
6667         schema->topgrammar = ret = xmlRelaxNGNewGrammar(ctxt);
6668         if (schema->topgrammar == NULL) {
6669             xmlRelaxNGFree(schema);
6670             return (NULL);
6671         }
6672         /*
6673          * Link the new grammar in the tree
6674          */
6675         ret->parent = ctxt->grammar;
6676         if (ctxt->grammar != NULL) {
6677             tmp = ctxt->grammar->children;
6678             if (tmp == NULL) {
6679                 ctxt->grammar->children = ret;
6680             } else {
6681                 while (tmp->next != NULL)
6682                     tmp = tmp->next;
6683                 tmp->next = ret;
6684             }
6685         }
6686         old = ctxt->grammar;
6687         ctxt->grammar = ret;
6688         xmlRelaxNGParseStart(ctxt, node);
6689         if (old != NULL)
6690             ctxt->grammar = old;
6691     }
6692     ctxt->define = olddefine;
6693     if (schema->topgrammar->start != NULL) {
6694         xmlRelaxNGCheckCycles(ctxt, schema->topgrammar->start, 0);
6695         if ((ctxt->flags & XML_RELAXNG_IN_EXTERNALREF) == 0) {
6696             xmlRelaxNGSimplify(ctxt, schema->topgrammar->start, NULL);
6697             while ((schema->topgrammar->start != NULL) &&
6698                    (schema->topgrammar->start->type == XML_RELAXNG_NOOP) &&
6699                    (schema->topgrammar->start->next != NULL))
6700                 schema->topgrammar->start =
6701                     schema->topgrammar->start->content;
6702             xmlRelaxNGCheckRules(ctxt, schema->topgrammar->start,
6703                                  XML_RELAXNG_IN_START, XML_RELAXNG_NOOP);
6704         }
6705     }
6706 #ifdef DEBUG
6707     if (schema == NULL)
6708         xmlGenericError(xmlGenericErrorContext,
6709                         "xmlRelaxNGParseDocument() failed\n");
6710 #endif
6711
6712     return (schema);
6713 }
6714
6715 /************************************************************************
6716  *                                                                      *
6717  *                      Reading RelaxNGs                                *
6718  *                                                                      *
6719  ************************************************************************/
6720
6721 /**
6722  * xmlRelaxNGNewParserCtxt:
6723  * @URL:  the location of the schema
6724  *
6725  * Create an XML RelaxNGs parse context for that file/resource expected
6726  * to contain an XML RelaxNGs file.
6727  *
6728  * Returns the parser context or NULL in case of error
6729  */
6730 xmlRelaxNGParserCtxtPtr
6731 xmlRelaxNGNewParserCtxt(const char *URL)
6732 {
6733     xmlRelaxNGParserCtxtPtr ret;
6734
6735     if (URL == NULL)
6736         return (NULL);
6737
6738     ret =
6739         (xmlRelaxNGParserCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGParserCtxt));
6740     if (ret == NULL) {
6741         xmlRngPErrMemory(NULL, "building parser\n");
6742         return (NULL);
6743     }
6744     memset(ret, 0, sizeof(xmlRelaxNGParserCtxt));
6745     ret->URL = xmlStrdup((const xmlChar *) URL);
6746     ret->error = xmlGenericError;
6747     ret->userData = xmlGenericErrorContext;
6748     return (ret);
6749 }
6750
6751 /**
6752  * xmlRelaxNGNewMemParserCtxt:
6753  * @buffer:  a pointer to a char array containing the schemas
6754  * @size:  the size of the array
6755  *
6756  * Create an XML RelaxNGs parse context for that memory buffer expected
6757  * to contain an XML RelaxNGs file.
6758  *
6759  * Returns the parser context or NULL in case of error
6760  */
6761 xmlRelaxNGParserCtxtPtr
6762 xmlRelaxNGNewMemParserCtxt(const char *buffer, int size)
6763 {
6764     xmlRelaxNGParserCtxtPtr ret;
6765
6766     if ((buffer == NULL) || (size <= 0))
6767         return (NULL);
6768
6769     ret =
6770         (xmlRelaxNGParserCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGParserCtxt));
6771     if (ret == NULL) {
6772         xmlRngPErrMemory(NULL, "building parser\n");
6773         return (NULL);
6774     }
6775     memset(ret, 0, sizeof(xmlRelaxNGParserCtxt));
6776     ret->buffer = buffer;
6777     ret->size = size;
6778     ret->error = xmlGenericError;
6779     ret->userData = xmlGenericErrorContext;
6780     return (ret);
6781 }
6782
6783 /**
6784  * xmlRelaxNGNewDocParserCtxt:
6785  * @doc:  a preparsed document tree
6786  *
6787  * Create an XML RelaxNGs parser context for that document.
6788  * Note: since the process of compiling a RelaxNG schemas modifies the
6789  *       document, the @doc parameter is duplicated internally.
6790  *
6791  * Returns the parser context or NULL in case of error
6792  */
6793 xmlRelaxNGParserCtxtPtr
6794 xmlRelaxNGNewDocParserCtxt(xmlDocPtr doc)
6795 {
6796     xmlRelaxNGParserCtxtPtr ret;
6797     xmlDocPtr copy;
6798
6799     if (doc == NULL)
6800         return (NULL);
6801     copy = xmlCopyDoc(doc, 1);
6802     if (copy == NULL)
6803         return (NULL);
6804
6805     ret =
6806         (xmlRelaxNGParserCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGParserCtxt));
6807     if (ret == NULL) {
6808         xmlRngPErrMemory(NULL, "building parser\n");
6809         return (NULL);
6810     }
6811     memset(ret, 0, sizeof(xmlRelaxNGParserCtxt));
6812     ret->document = copy;
6813     ret->freedoc = 1;
6814     ret->userData = xmlGenericErrorContext;
6815     return (ret);
6816 }
6817
6818 /**
6819  * xmlRelaxNGFreeParserCtxt:
6820  * @ctxt:  the schema parser context
6821  *
6822  * Free the resources associated to the schema parser context
6823  */
6824 void
6825 xmlRelaxNGFreeParserCtxt(xmlRelaxNGParserCtxtPtr ctxt)
6826 {
6827     if (ctxt == NULL)
6828         return;
6829     if (ctxt->URL != NULL)
6830         xmlFree(ctxt->URL);
6831     if (ctxt->doc != NULL)
6832         xmlRelaxNGFreeDocument(ctxt->doc);
6833     if (ctxt->interleaves != NULL)
6834         xmlHashFree(ctxt->interleaves, NULL);
6835     if (ctxt->documents != NULL)
6836         xmlRelaxNGFreeDocumentList(ctxt->documents);
6837     if (ctxt->includes != NULL)
6838         xmlRelaxNGFreeIncludeList(ctxt->includes);
6839     if (ctxt->docTab != NULL)
6840         xmlFree(ctxt->docTab);
6841     if (ctxt->incTab != NULL)
6842         xmlFree(ctxt->incTab);
6843     if (ctxt->defTab != NULL) {
6844         int i;
6845
6846         for (i = 0; i < ctxt->defNr; i++)
6847             xmlRelaxNGFreeDefine(ctxt->defTab[i]);
6848         xmlFree(ctxt->defTab);
6849     }
6850     if ((ctxt->document != NULL) && (ctxt->freedoc))
6851         xmlFreeDoc(ctxt->document);
6852     xmlFree(ctxt);
6853 }
6854
6855 /**
6856  * xmlRelaxNGNormExtSpace:
6857  * @value:  a value
6858  *
6859  * Removes the leading and ending spaces of the value
6860  * The string is modified "in situ"
6861  */
6862 static void
6863 xmlRelaxNGNormExtSpace(xmlChar * value)
6864 {
6865     xmlChar *start = value;
6866     xmlChar *cur = value;
6867
6868     if (value == NULL)
6869         return;
6870
6871     while (IS_BLANK_CH(*cur))
6872         cur++;
6873     if (cur == start) {
6874         do {
6875             while ((*cur != 0) && (!IS_BLANK_CH(*cur)))
6876                 cur++;
6877             if (*cur == 0)
6878                 return;
6879             start = cur;
6880             while (IS_BLANK_CH(*cur))
6881                 cur++;
6882             if (*cur == 0) {
6883                 *start = 0;
6884                 return;
6885             }
6886         } while (1);
6887     } else {
6888         do {
6889             while ((*cur != 0) && (!IS_BLANK_CH(*cur)))
6890                 *start++ = *cur++;
6891             if (*cur == 0) {
6892                 *start = 0;
6893                 return;
6894             }
6895             /* don't try to normalize the inner spaces */
6896             while (IS_BLANK_CH(*cur))
6897                 cur++;
6898             if (*cur == 0) {
6899                 *start = 0;
6900                 return;
6901             }
6902             *start++ = *cur++;
6903         } while (1);
6904     }
6905 }
6906
6907 /**
6908  * xmlRelaxNGCleanupAttributes:
6909  * @ctxt:  a Relax-NG parser context
6910  * @node:  a Relax-NG node
6911  *
6912  * Check all the attributes on the given node
6913  */
6914 static void
6915 xmlRelaxNGCleanupAttributes(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
6916 {
6917     xmlAttrPtr cur, next;
6918
6919     cur = node->properties;
6920     while (cur != NULL) {
6921         next = cur->next;
6922         if ((cur->ns == NULL) ||
6923             (xmlStrEqual(cur->ns->href, xmlRelaxNGNs))) {
6924             if (xmlStrEqual(cur->name, BAD_CAST "name")) {
6925                 if ((!xmlStrEqual(node->name, BAD_CAST "element")) &&
6926                     (!xmlStrEqual(node->name, BAD_CAST "attribute")) &&
6927                     (!xmlStrEqual(node->name, BAD_CAST "ref")) &&
6928                     (!xmlStrEqual(node->name, BAD_CAST "parentRef")) &&
6929                     (!xmlStrEqual(node->name, BAD_CAST "param")) &&
6930                     (!xmlStrEqual(node->name, BAD_CAST "define"))) {
6931                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6932                                "Attribute %s is not allowed on %s\n",
6933                                cur->name, node->name);
6934                 }
6935             } else if (xmlStrEqual(cur->name, BAD_CAST "type")) {
6936                 if ((!xmlStrEqual(node->name, BAD_CAST "value")) &&
6937                     (!xmlStrEqual(node->name, BAD_CAST "data"))) {
6938                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6939                                "Attribute %s is not allowed on %s\n",
6940                                cur->name, node->name);
6941                 }
6942             } else if (xmlStrEqual(cur->name, BAD_CAST "href")) {
6943                 if ((!xmlStrEqual(node->name, BAD_CAST "externalRef")) &&
6944                     (!xmlStrEqual(node->name, BAD_CAST "include"))) {
6945                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6946                                "Attribute %s is not allowed on %s\n",
6947                                cur->name, node->name);
6948                 }
6949             } else if (xmlStrEqual(cur->name, BAD_CAST "combine")) {
6950                 if ((!xmlStrEqual(node->name, BAD_CAST "start")) &&
6951                     (!xmlStrEqual(node->name, BAD_CAST "define"))) {
6952                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6953                                "Attribute %s is not allowed on %s\n",
6954                                cur->name, node->name);
6955                 }
6956             } else if (xmlStrEqual(cur->name, BAD_CAST "datatypeLibrary")) {
6957                 xmlChar *val;
6958                 xmlURIPtr uri;
6959
6960                 val = xmlNodeListGetString(node->doc, cur->children, 1);
6961                 if (val != NULL) {
6962                     if (val[0] != 0) {
6963                         uri = xmlParseURI((const char *) val);
6964                         if (uri == NULL) {
6965                             xmlRngPErr(ctxt, node, XML_RNGP_INVALID_URI,
6966                                        "Attribute %s contains invalid URI %s\n",
6967                                        cur->name, val);
6968                         } else {
6969                             if (uri->scheme == NULL) {
6970                                 xmlRngPErr(ctxt, node, XML_RNGP_URI_NOT_ABSOLUTE,
6971                                            "Attribute %s URI %s is not absolute\n",
6972                                            cur->name, val);
6973                             }
6974                             if (uri->fragment != NULL) {
6975                                 xmlRngPErr(ctxt, node, XML_RNGP_URI_FRAGMENT,
6976                                            "Attribute %s URI %s has a fragment ID\n",
6977                                            cur->name, val);
6978                             }
6979                             xmlFreeURI(uri);
6980                         }
6981                     }
6982                     xmlFree(val);
6983                 }
6984             } else if (!xmlStrEqual(cur->name, BAD_CAST "ns")) {
6985                 xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_ATTRIBUTE,
6986                            "Unknown attribute %s on %s\n", cur->name,
6987                            node->name);
6988             }
6989         }
6990         cur = next;
6991     }
6992 }
6993
6994 /**
6995  * xmlRelaxNGCleanupTree:
6996  * @ctxt:  a Relax-NG parser context
6997  * @root:  an xmlNodePtr subtree
6998  *
6999  * Cleanup the subtree from unwanted nodes for parsing, resolve
7000  * Include and externalRef lookups.
7001  */
7002 static void
7003 xmlRelaxNGCleanupTree(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr root)
7004 {
7005     xmlNodePtr cur, delete;
7006
7007     delete = NULL;
7008     cur = root;
7009     while (cur != NULL) {
7010         if (delete != NULL) {
7011             xmlUnlinkNode(delete);
7012             xmlFreeNode(delete);
7013             delete = NULL;
7014         }
7015         if (cur->type == XML_ELEMENT_NODE) {
7016             /*
7017              * Simplification 4.1. Annotations
7018              */
7019             if ((cur->ns == NULL) ||
7020                 (!xmlStrEqual(cur->ns->href, xmlRelaxNGNs))) {
7021                 if ((cur->parent != NULL) &&
7022                     (cur->parent->type == XML_ELEMENT_NODE) &&
7023                     ((xmlStrEqual(cur->parent->name, BAD_CAST "name")) ||
7024                      (xmlStrEqual(cur->parent->name, BAD_CAST "value")) ||
7025                      (xmlStrEqual(cur->parent->name, BAD_CAST "param")))) {
7026                     xmlRngPErr(ctxt, cur, XML_RNGP_FOREIGN_ELEMENT,
7027                                "element %s doesn't allow foreign elements\n",
7028                                cur->parent->name, NULL);
7029                 }
7030                 delete = cur;
7031                 goto skip_children;
7032             } else {
7033                 xmlRelaxNGCleanupAttributes(ctxt, cur);
7034                 if (xmlStrEqual(cur->name, BAD_CAST "externalRef")) {
7035                     xmlChar *href, *ns, *base, *URL;
7036                     xmlRelaxNGDocumentPtr docu;
7037                     xmlNodePtr tmp;
7038                     xmlURIPtr uri;
7039
7040                     ns = xmlGetProp(cur, BAD_CAST "ns");
7041                     if (ns == NULL) {
7042                         tmp = cur->parent;
7043                         while ((tmp != NULL) &&
7044                                (tmp->type == XML_ELEMENT_NODE)) {
7045                             ns = xmlGetProp(tmp, BAD_CAST "ns");
7046                             if (ns != NULL)
7047                                 break;
7048                             tmp = tmp->parent;
7049                         }
7050                     }
7051                     href = xmlGetProp(cur, BAD_CAST "href");
7052                     if (href == NULL) {
7053                         xmlRngPErr(ctxt, cur, XML_RNGP_MISSING_HREF,
7054                                    "xmlRelaxNGParse: externalRef has no href attribute\n",
7055                                    NULL, NULL);
7056                         if (ns != NULL)
7057                             xmlFree(ns);
7058                         delete = cur;
7059                         goto skip_children;
7060                     }
7061                     uri = xmlParseURI((const char *) href);
7062                     if (uri == NULL) {
7063                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
7064                                    "Incorrect URI for externalRef %s\n",
7065                                    href, NULL);
7066                         if (ns != NULL)
7067                             xmlFree(ns);
7068                         if (href != NULL)
7069                             xmlFree(href);
7070                         delete = cur;
7071                         goto skip_children;
7072                     }
7073                     if (uri->fragment != NULL) {
7074                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
7075                                "Fragment forbidden in URI for externalRef %s\n",
7076                                    href, NULL);
7077                         if (ns != NULL)
7078                             xmlFree(ns);
7079                         xmlFreeURI(uri);
7080                         if (href != NULL)
7081                             xmlFree(href);
7082                         delete = cur;
7083                         goto skip_children;
7084                     }
7085                     xmlFreeURI(uri);
7086                     base = xmlNodeGetBase(cur->doc, cur);
7087                     URL = xmlBuildURI(href, base);
7088                     if (URL == NULL) {
7089                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
7090                                    "Failed to compute URL for externalRef %s\n",
7091                                    href, NULL);
7092                         if (ns != NULL)
7093                             xmlFree(ns);
7094                         if (href != NULL)
7095                             xmlFree(href);
7096                         if (base != NULL)
7097                             xmlFree(base);
7098                         delete = cur;
7099                         goto skip_children;
7100                     }
7101                     if (href != NULL)
7102                         xmlFree(href);
7103                     if (base != NULL)
7104                         xmlFree(base);
7105                     docu = xmlRelaxNGLoadExternalRef(ctxt, URL, ns);
7106                     if (docu == NULL) {
7107                         xmlRngPErr(ctxt, cur, XML_RNGP_EXTERNAL_REF_FAILURE,
7108                                    "Failed to load externalRef %s\n", URL,
7109                                    NULL);
7110                         if (ns != NULL)
7111                             xmlFree(ns);
7112                         xmlFree(URL);
7113                         delete = cur;
7114                         goto skip_children;
7115                     }
7116                     if (ns != NULL)
7117                         xmlFree(ns);
7118                     xmlFree(URL);
7119                     cur->psvi = docu;
7120                 } else if (xmlStrEqual(cur->name, BAD_CAST "include")) {
7121                     xmlChar *href, *ns, *base, *URL;
7122                     xmlRelaxNGIncludePtr incl;
7123                     xmlNodePtr tmp;
7124
7125                     href = xmlGetProp(cur, BAD_CAST "href");
7126                     if (href == NULL) {
7127                         xmlRngPErr(ctxt, cur, XML_RNGP_MISSING_HREF,
7128                                    "xmlRelaxNGParse: include has no href attribute\n",
7129                                    NULL, NULL);
7130                         delete = cur;
7131                         goto skip_children;
7132                     }
7133                     base = xmlNodeGetBase(cur->doc, cur);
7134                     URL = xmlBuildURI(href, base);
7135                     if (URL == NULL) {
7136                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
7137                                    "Failed to compute URL for include %s\n",
7138                                    href, NULL);
7139                         if (href != NULL)
7140                             xmlFree(href);
7141                         if (base != NULL)
7142                             xmlFree(base);
7143                         delete = cur;
7144                         goto skip_children;
7145                     }
7146                     if (href != NULL)
7147                         xmlFree(href);
7148                     if (base != NULL)
7149                         xmlFree(base);
7150                     ns = xmlGetProp(cur, BAD_CAST "ns");
7151                     if (ns == NULL) {
7152                         tmp = cur->parent;
7153                         while ((tmp != NULL) &&
7154                                (tmp->type == XML_ELEMENT_NODE)) {
7155                             ns = xmlGetProp(tmp, BAD_CAST "ns");
7156                             if (ns != NULL)
7157                                 break;
7158                             tmp = tmp->parent;
7159                         }
7160                     }
7161                     incl = xmlRelaxNGLoadInclude(ctxt, URL, cur, ns);
7162                     if (ns != NULL)
7163                         xmlFree(ns);
7164                     if (incl == NULL) {
7165                         xmlRngPErr(ctxt, cur, XML_RNGP_INCLUDE_FAILURE,
7166                                    "Failed to load include %s\n", URL,
7167                                    NULL);
7168                         xmlFree(URL);
7169                         delete = cur;
7170                         goto skip_children;
7171                     }
7172                     xmlFree(URL);
7173                     cur->psvi = incl;
7174                 } else if ((xmlStrEqual(cur->name, BAD_CAST "element")) ||
7175                            (xmlStrEqual(cur->name, BAD_CAST "attribute")))
7176                 {
7177                     xmlChar *name, *ns;
7178                     xmlNodePtr text = NULL;
7179
7180                     /*
7181                      * Simplification 4.8. name attribute of element
7182                      * and attribute elements
7183                      */
7184                     name = xmlGetProp(cur, BAD_CAST "name");
7185                     if (name != NULL) {
7186                         if (cur->children == NULL) {
7187                             text =
7188                                 xmlNewChild(cur, cur->ns, BAD_CAST "name",
7189                                             name);
7190                         } else {
7191                             xmlNodePtr node;
7192
7193                             node = xmlNewDocNode(cur->doc, cur->ns,
7194                                                  BAD_CAST "name", NULL);
7195                             if (node != NULL) {
7196                                 xmlAddPrevSibling(cur->children, node);
7197                                 text = xmlNewText(name);
7198                                 xmlAddChild(node, text);
7199                                 text = node;
7200                             }
7201                         }
7202                         if (text == NULL) {
7203                             xmlRngPErr(ctxt, cur, XML_RNGP_CREATE_FAILURE,
7204                                        "Failed to create a name %s element\n",
7205                                        name, NULL);
7206                         }
7207                         xmlUnsetProp(cur, BAD_CAST "name");
7208                         xmlFree(name);
7209                         ns = xmlGetProp(cur, BAD_CAST "ns");
7210                         if (ns != NULL) {
7211                             if (text != NULL) {
7212                                 xmlSetProp(text, BAD_CAST "ns", ns);
7213                                 /* xmlUnsetProp(cur, BAD_CAST "ns"); */
7214                             }
7215                             xmlFree(ns);
7216                         } else if (xmlStrEqual(cur->name,
7217                                                BAD_CAST "attribute")) {
7218                             xmlSetProp(text, BAD_CAST "ns", BAD_CAST "");
7219                         }
7220                     }
7221                 } else if ((xmlStrEqual(cur->name, BAD_CAST "name")) ||
7222                            (xmlStrEqual(cur->name, BAD_CAST "nsName")) ||
7223                            (xmlStrEqual(cur->name, BAD_CAST "value"))) {
7224                     /*
7225                      * Simplification 4.8. name attribute of element
7226                      * and attribute elements
7227                      */
7228                     if (xmlHasProp(cur, BAD_CAST "ns") == NULL) {
7229                         xmlNodePtr node;
7230                         xmlChar *ns = NULL;
7231
7232                         node = cur->parent;
7233                         while ((node != NULL) &&
7234                                (node->type == XML_ELEMENT_NODE)) {
7235                             ns = xmlGetProp(node, BAD_CAST "ns");
7236                             if (ns != NULL) {
7237                                 break;
7238                             }
7239                             node = node->parent;
7240                         }
7241                         if (ns == NULL) {
7242                             xmlSetProp(cur, BAD_CAST "ns", BAD_CAST "");
7243                         } else {
7244                             xmlSetProp(cur, BAD_CAST "ns", ns);
7245                             xmlFree(ns);
7246                         }
7247                     }
7248                     if (xmlStrEqual(cur->name, BAD_CAST "name")) {
7249                         xmlChar *name, *local, *prefix;
7250
7251                         /*
7252                          * Simplification: 4.10. QNames
7253                          */
7254                         name = xmlNodeGetContent(cur);
7255                         if (name != NULL) {
7256                             local = xmlSplitQName2(name, &prefix);
7257                             if (local != NULL) {
7258                                 xmlNsPtr ns;
7259
7260                                 ns = xmlSearchNs(cur->doc, cur, prefix);
7261                                 if (ns == NULL) {
7262                                     xmlRngPErr(ctxt, cur,
7263                                                XML_RNGP_PREFIX_UNDEFINED,
7264                                                "xmlRelaxNGParse: no namespace for prefix %s\n",
7265                                                prefix, NULL);
7266                                 } else {
7267                                     xmlSetProp(cur, BAD_CAST "ns",
7268                                                ns->href);
7269                                     xmlNodeSetContent(cur, local);
7270                                 }
7271                                 xmlFree(local);
7272                                 xmlFree(prefix);
7273                             }
7274                             xmlFree(name);
7275                         }
7276                     }
7277                     /*
7278                      * 4.16
7279                      */
7280                     if (xmlStrEqual(cur->name, BAD_CAST "nsName")) {
7281                         if (ctxt->flags & XML_RELAXNG_IN_NSEXCEPT) {
7282                             xmlRngPErr(ctxt, cur,
7283                                        XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME,
7284                                        "Found nsName/except//nsName forbidden construct\n",
7285                                        NULL, NULL);
7286                         }
7287                     }
7288                 } else if ((xmlStrEqual(cur->name, BAD_CAST "except")) &&
7289                            (cur != root)) {
7290                     int oldflags = ctxt->flags;
7291
7292                     /*
7293                      * 4.16
7294                      */
7295                     if ((cur->parent != NULL) &&
7296                         (xmlStrEqual
7297                          (cur->parent->name, BAD_CAST "anyName"))) {
7298                         ctxt->flags |= XML_RELAXNG_IN_ANYEXCEPT;
7299                         xmlRelaxNGCleanupTree(ctxt, cur);
7300                         ctxt->flags = oldflags;
7301                         goto skip_children;
7302                     } else if ((cur->parent != NULL) &&
7303                                (xmlStrEqual
7304                                 (cur->parent->name, BAD_CAST "nsName"))) {
7305                         ctxt->flags |= XML_RELAXNG_IN_NSEXCEPT;
7306                         xmlRelaxNGCleanupTree(ctxt, cur);
7307                         ctxt->flags = oldflags;
7308                         goto skip_children;
7309                     }
7310                 } else if (xmlStrEqual(cur->name, BAD_CAST "anyName")) {
7311                     /*
7312                      * 4.16
7313                      */
7314                     if (ctxt->flags & XML_RELAXNG_IN_ANYEXCEPT) {
7315                         xmlRngPErr(ctxt, cur,
7316                                    XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME,
7317                                    "Found anyName/except//anyName forbidden construct\n",
7318                                    NULL, NULL);
7319                     } else if (ctxt->flags & XML_RELAXNG_IN_NSEXCEPT) {
7320                         xmlRngPErr(ctxt, cur,
7321                                    XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME,
7322                                    "Found nsName/except//anyName forbidden construct\n",
7323                                    NULL, NULL);
7324                     }
7325                 }
7326                 /*
7327                  * This is not an else since "include" is transformed
7328                  * into a div
7329                  */
7330                 if (xmlStrEqual(cur->name, BAD_CAST "div")) {
7331                     xmlChar *ns;
7332                     xmlNodePtr child, ins, tmp;
7333
7334                     /*
7335                      * implements rule 4.11
7336                      */
7337
7338                     ns = xmlGetProp(cur, BAD_CAST "ns");
7339
7340                     child = cur->children;
7341                     ins = cur;
7342                     while (child != NULL) {
7343                         if (ns != NULL) {
7344                             if (!xmlHasProp(child, BAD_CAST "ns")) {
7345                                 xmlSetProp(child, BAD_CAST "ns", ns);
7346                             }
7347                         }
7348                         tmp = child->next;
7349                         xmlUnlinkNode(child);
7350                         ins = xmlAddNextSibling(ins, child);
7351                         child = tmp;
7352                     }
7353                     if (ns != NULL)
7354                         xmlFree(ns);
7355                     /*
7356                      * Since we are about to delete cur, if its nsDef is non-NULL we
7357                      * need to preserve it (it contains the ns definitions for the
7358                      * children we just moved).  We'll just stick it on to the end
7359                      * of cur->parent's list, since it's never going to be re-serialized
7360                      * (bug 143738).
7361                      */
7362                     if ((cur->nsDef != NULL) && (cur->parent != NULL)) {
7363                         xmlNsPtr parDef = (xmlNsPtr)&cur->parent->nsDef;
7364                         while (parDef->next != NULL)
7365                             parDef = parDef->next;
7366                         parDef->next = cur->nsDef;
7367                         cur->nsDef = NULL;
7368                     }
7369                     delete = cur;
7370                     goto skip_children;
7371                 }
7372             }
7373         }
7374         /*
7375          * Simplification 4.2 whitespaces
7376          */
7377         else if ((cur->type == XML_TEXT_NODE) ||
7378                  (cur->type == XML_CDATA_SECTION_NODE)) {
7379             if (IS_BLANK_NODE(cur)) {
7380                 if ((cur->parent != NULL) &&
7381                     (cur->parent->type == XML_ELEMENT_NODE)) {
7382                     if ((!xmlStrEqual(cur->parent->name, BAD_CAST "value"))
7383                         &&
7384                         (!xmlStrEqual
7385                          (cur->parent->name, BAD_CAST "param")))
7386                         delete = cur;
7387                 } else {
7388                     delete = cur;
7389                     goto skip_children;
7390                 }
7391             }
7392         } else {
7393             delete = cur;
7394             goto skip_children;
7395         }
7396
7397         /*
7398          * Skip to next node
7399          */
7400         if (cur->children != NULL) {
7401             if ((cur->children->type != XML_ENTITY_DECL) &&
7402                 (cur->children->type != XML_ENTITY_REF_NODE) &&
7403                 (cur->children->type != XML_ENTITY_NODE)) {
7404                 cur = cur->children;
7405                 continue;
7406             }
7407         }
7408       skip_children:
7409         if (cur->next != NULL) {
7410             cur = cur->next;
7411             continue;
7412         }
7413
7414         do {
7415             cur = cur->parent;
7416             if (cur == NULL)
7417                 break;
7418             if (cur == root) {
7419                 cur = NULL;
7420                 break;
7421             }
7422             if (cur->next != NULL) {
7423                 cur = cur->next;
7424                 break;
7425             }
7426         } while (cur != NULL);
7427     }
7428     if (delete != NULL) {
7429         xmlUnlinkNode(delete);
7430         xmlFreeNode(delete);
7431         delete = NULL;
7432     }
7433 }
7434
7435 /**
7436  * xmlRelaxNGCleanupDoc:
7437  * @ctxt:  a Relax-NG parser context
7438  * @doc:  an xmldocPtr document pointer
7439  *
7440  * Cleanup the document from unwanted nodes for parsing, resolve
7441  * Include and externalRef lookups.
7442  *
7443  * Returns the cleaned up document or NULL in case of error
7444  */
7445 static xmlDocPtr
7446 xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt, xmlDocPtr doc)
7447 {
7448     xmlNodePtr root;
7449
7450     /*
7451      * Extract the root
7452      */
7453     root = xmlDocGetRootElement(doc);
7454     if (root == NULL) {
7455         xmlRngPErr(ctxt, (xmlNodePtr) doc, XML_RNGP_EMPTY, "xmlRelaxNGParse: %s is empty\n",
7456                    ctxt->URL, NULL);
7457         return (NULL);
7458     }
7459     xmlRelaxNGCleanupTree(ctxt, root);
7460     return (doc);
7461 }
7462
7463 /**
7464  * xmlRelaxNGParse:
7465  * @ctxt:  a Relax-NG parser context
7466  *
7467  * parse a schema definition resource and build an internal
7468  * XML Shema struture which can be used to validate instances.
7469  *
7470  * Returns the internal XML RelaxNG structure built from the resource or
7471  *         NULL in case of error
7472  */
7473 xmlRelaxNGPtr
7474 xmlRelaxNGParse(xmlRelaxNGParserCtxtPtr ctxt)
7475 {
7476     xmlRelaxNGPtr ret = NULL;
7477     xmlDocPtr doc;
7478     xmlNodePtr root;
7479
7480     xmlRelaxNGInitTypes();
7481
7482     if (ctxt == NULL)
7483         return (NULL);
7484
7485     /*
7486      * First step is to parse the input document into an DOM/Infoset
7487      */
7488     if (ctxt->URL != NULL) {
7489         doc = xmlReadFile((const char *) ctxt->URL,NULL,0);
7490         if (doc == NULL) {
7491             xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,
7492                        "xmlRelaxNGParse: could not load %s\n", ctxt->URL,
7493                        NULL);
7494             return (NULL);
7495         }
7496     } else if (ctxt->buffer != NULL) {
7497         doc = xmlReadMemory(ctxt->buffer, ctxt->size,NULL,NULL,0);
7498         if (doc == NULL) {
7499             xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,
7500                        "xmlRelaxNGParse: could not parse schemas\n", NULL,
7501                        NULL);
7502             return (NULL);
7503         }
7504         doc->URL = xmlStrdup(BAD_CAST "in_memory_buffer");
7505         ctxt->URL = xmlStrdup(BAD_CAST "in_memory_buffer");
7506     } else if (ctxt->document != NULL) {
7507         doc = ctxt->document;
7508     } else {
7509         xmlRngPErr(ctxt, NULL, XML_RNGP_EMPTY,
7510                    "xmlRelaxNGParse: nothing to parse\n", NULL, NULL);
7511         return (NULL);
7512     }
7513     ctxt->document = doc;
7514
7515     /*
7516      * Some preprocessing of the document content
7517      */
7518     doc = xmlRelaxNGCleanupDoc(ctxt, doc);
7519     if (doc == NULL) {
7520         xmlFreeDoc(ctxt->document);
7521         ctxt->document = NULL;
7522         return (NULL);
7523     }
7524
7525     /*
7526      * Then do the parsing for good
7527      */
7528     root = xmlDocGetRootElement(doc);
7529     if (root == NULL) {
7530         xmlRngPErr(ctxt, (xmlNodePtr) doc,
7531                    XML_RNGP_EMPTY, "xmlRelaxNGParse: %s is empty\n",
7532                    (ctxt->URL ? ctxt->URL : BAD_CAST "schemas"), NULL);
7533
7534         xmlFreeDoc(ctxt->document);
7535         ctxt->document = NULL;
7536         return (NULL);
7537     }
7538     ret = xmlRelaxNGParseDocument(ctxt, root);
7539     if (ret == NULL) {
7540         xmlFreeDoc(ctxt->document);
7541         ctxt->document = NULL;
7542         return (NULL);
7543     }
7544
7545     /*
7546      * Check the ref/defines links
7547      */
7548     /*
7549      * try to preprocess interleaves
7550      */
7551     if (ctxt->interleaves != NULL) {
7552         xmlHashScan(ctxt->interleaves,
7553                     (xmlHashScanner) xmlRelaxNGComputeInterleaves, ctxt);
7554     }
7555
7556     /*
7557      * if there was a parsing error return NULL
7558      */
7559     if (ctxt->nbErrors > 0) {
7560         xmlRelaxNGFree(ret);
7561         ctxt->document = NULL;
7562         xmlFreeDoc(doc);
7563         return (NULL);
7564     }
7565
7566     /*
7567      * try to compile (parts of) the schemas
7568      */
7569     if ((ret->topgrammar != NULL) && (ret->topgrammar->start != NULL)) {
7570         if (ret->topgrammar->start->type != XML_RELAXNG_START) {
7571             xmlRelaxNGDefinePtr def;
7572
7573             def = xmlRelaxNGNewDefine(ctxt, NULL);
7574             if (def != NULL) {
7575                 def->type = XML_RELAXNG_START;
7576                 def->content = ret->topgrammar->start;
7577                 ret->topgrammar->start = def;
7578             }
7579         }
7580         xmlRelaxNGTryCompile(ctxt, ret->topgrammar->start);
7581     }
7582
7583     /*
7584      * Transfer the pointer for cleanup at the schema level.
7585      */
7586     ret->doc = doc;
7587     ctxt->document = NULL;
7588     ret->documents = ctxt->documents;
7589     ctxt->documents = NULL;
7590
7591     ret->includes = ctxt->includes;
7592     ctxt->includes = NULL;
7593     ret->defNr = ctxt->defNr;
7594     ret->defTab = ctxt->defTab;
7595     ctxt->defTab = NULL;
7596     if (ctxt->idref == 1)
7597         ret->idref = 1;
7598
7599     return (ret);
7600 }
7601
7602 /**
7603  * xmlRelaxNGSetParserErrors:
7604  * @ctxt:  a Relax-NG validation context
7605  * @err:  the error callback
7606  * @warn:  the warning callback
7607  * @ctx:  contextual data for the callbacks
7608  *
7609  * Set the callback functions used to handle errors for a validation context
7610  */
7611 void
7612 xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
7613                           xmlRelaxNGValidityErrorFunc err,
7614                           xmlRelaxNGValidityWarningFunc warn, void *ctx)
7615 {
7616     if (ctxt == NULL)
7617         return;
7618     ctxt->error = err;
7619     ctxt->warning = warn;
7620     ctxt->serror = NULL;
7621     ctxt->userData = ctx;
7622 }
7623
7624 /**
7625  * xmlRelaxNGGetParserErrors:
7626  * @ctxt:  a Relax-NG validation context
7627  * @err:  the error callback result
7628  * @warn:  the warning callback result
7629  * @ctx:  contextual data for the callbacks result
7630  *
7631  * Get the callback information used to handle errors for a validation context
7632  *
7633  * Returns -1 in case of failure, 0 otherwise.
7634  */
7635 int
7636 xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
7637                           xmlRelaxNGValidityErrorFunc * err,
7638                           xmlRelaxNGValidityWarningFunc * warn, void **ctx)
7639 {
7640     if (ctxt == NULL)
7641         return (-1);
7642     if (err != NULL)
7643         *err = ctxt->error;
7644     if (warn != NULL)
7645         *warn = ctxt->warning;
7646     if (ctx != NULL)
7647         *ctx = ctxt->userData;
7648     return (0);
7649 }
7650
7651 /**
7652  * xmlRelaxNGSetParserStructuredErrors:
7653  * @ctxt:  a Relax-NG parser context
7654  * @serror:  the error callback
7655  * @ctx:  contextual data for the callbacks
7656  *
7657  * Set the callback functions used to handle errors for a parsing context
7658  */
7659 void
7660 xmlRelaxNGSetParserStructuredErrors(xmlRelaxNGParserCtxtPtr ctxt,
7661                                     xmlStructuredErrorFunc serror,
7662                                     void *ctx)
7663 {
7664     if (ctxt == NULL)
7665         return;
7666     ctxt->serror = serror;
7667     ctxt->error = NULL;
7668     ctxt->warning = NULL;
7669     ctxt->userData = ctx;
7670 }
7671
7672 #ifdef LIBXML_OUTPUT_ENABLED
7673
7674 /************************************************************************
7675  *                                                                      *
7676  *                      Dump back a compiled form                       *
7677  *                                                                      *
7678  ************************************************************************/
7679 static void xmlRelaxNGDumpDefine(FILE * output,
7680                                  xmlRelaxNGDefinePtr define);
7681
7682 /**
7683  * xmlRelaxNGDumpDefines:
7684  * @output:  the file output
7685  * @defines:  a list of define structures
7686  *
7687  * Dump a RelaxNG structure back
7688  */
7689 static void
7690 xmlRelaxNGDumpDefines(FILE * output, xmlRelaxNGDefinePtr defines)
7691 {
7692     while (defines != NULL) {
7693         xmlRelaxNGDumpDefine(output, defines);
7694         defines = defines->next;
7695     }
7696 }
7697
7698 /**
7699  * xmlRelaxNGDumpDefine:
7700  * @output:  the file output
7701  * @define:  a define structure
7702  *
7703  * Dump a RelaxNG structure back
7704  */
7705 static void
7706 xmlRelaxNGDumpDefine(FILE * output, xmlRelaxNGDefinePtr define)
7707 {
7708     if (define == NULL)
7709         return;
7710     switch (define->type) {
7711         case XML_RELAXNG_EMPTY:
7712             fprintf(output, "<empty/>\n");
7713             break;
7714         case XML_RELAXNG_NOT_ALLOWED:
7715             fprintf(output, "<notAllowed/>\n");
7716             break;
7717         case XML_RELAXNG_TEXT:
7718             fprintf(output, "<text/>\n");
7719             break;
7720         case XML_RELAXNG_ELEMENT:
7721             fprintf(output, "<element>\n");
7722             if (define->name != NULL) {
7723                 fprintf(output, "<name");
7724                 if (define->ns != NULL)
7725                     fprintf(output, " ns=\"%s\"", define->ns);
7726                 fprintf(output, ">%s</name>\n", define->name);
7727             }
7728             xmlRelaxNGDumpDefines(output, define->attrs);
7729             xmlRelaxNGDumpDefines(output, define->content);
7730             fprintf(output, "</element>\n");
7731             break;
7732         case XML_RELAXNG_LIST:
7733             fprintf(output, "<list>\n");
7734             xmlRelaxNGDumpDefines(output, define->content);
7735             fprintf(output, "</list>\n");
7736             break;
7737         case XML_RELAXNG_ONEORMORE:
7738             fprintf(output, "<oneOrMore>\n");
7739             xmlRelaxNGDumpDefines(output, define->content);
7740             fprintf(output, "</oneOrMore>\n");
7741             break;
7742         case XML_RELAXNG_ZEROORMORE:
7743             fprintf(output, "<zeroOrMore>\n");
7744             xmlRelaxNGDumpDefines(output, define->content);
7745             fprintf(output, "</zeroOrMore>\n");
7746             break;
7747         case XML_RELAXNG_CHOICE:
7748             fprintf(output, "<choice>\n");
7749             xmlRelaxNGDumpDefines(output, define->content);
7750             fprintf(output, "</choice>\n");
7751             break;
7752         case XML_RELAXNG_GROUP:
7753             fprintf(output, "<group>\n");
7754             xmlRelaxNGDumpDefines(output, define->content);
7755             fprintf(output, "</group>\n");
7756             break;
7757         case XML_RELAXNG_INTERLEAVE:
7758             fprintf(output, "<interleave>\n");
7759             xmlRelaxNGDumpDefines(output, define->content);
7760             fprintf(output, "</interleave>\n");
7761             break;
7762         case XML_RELAXNG_OPTIONAL:
7763             fprintf(output, "<optional>\n");
7764             xmlRelaxNGDumpDefines(output, define->content);
7765             fprintf(output, "</optional>\n");
7766             break;
7767         case XML_RELAXNG_ATTRIBUTE:
7768             fprintf(output, "<attribute>\n");
7769             xmlRelaxNGDumpDefines(output, define->content);
7770             fprintf(output, "</attribute>\n");
7771             break;
7772         case XML_RELAXNG_DEF:
7773             fprintf(output, "<define");
7774             if (define->name != NULL)
7775                 fprintf(output, " name=\"%s\"", define->name);
7776             fprintf(output, ">\n");
7777             xmlRelaxNGDumpDefines(output, define->content);
7778             fprintf(output, "</define>\n");
7779             break;
7780         case XML_RELAXNG_REF:
7781             fprintf(output, "<ref");
7782             if (define->name != NULL)
7783                 fprintf(output, " name=\"%s\"", define->name);
7784             fprintf(output, ">\n");
7785             xmlRelaxNGDumpDefines(output, define->content);
7786             fprintf(output, "</ref>\n");
7787             break;
7788         case XML_RELAXNG_PARENTREF:
7789             fprintf(output, "<parentRef");
7790             if (define->name != NULL)
7791                 fprintf(output, " name=\"%s\"", define->name);
7792             fprintf(output, ">\n");
7793             xmlRelaxNGDumpDefines(output, define->content);
7794             fprintf(output, "</parentRef>\n");
7795             break;
7796         case XML_RELAXNG_EXTERNALREF:
7797             fprintf(output, "<externalRef>");
7798             xmlRelaxNGDumpDefines(output, define->content);
7799             fprintf(output, "</externalRef>\n");
7800             break;
7801         case XML_RELAXNG_DATATYPE:
7802         case XML_RELAXNG_VALUE:
7803             TODO break;
7804         case XML_RELAXNG_START:
7805         case XML_RELAXNG_EXCEPT:
7806         case XML_RELAXNG_PARAM:
7807             TODO break;
7808         case XML_RELAXNG_NOOP:
7809             xmlRelaxNGDumpDefines(output, define->content);
7810             break;
7811     }
7812 }
7813
7814 /**
7815  * xmlRelaxNGDumpGrammar:
7816  * @output:  the file output
7817  * @grammar:  a grammar structure
7818  * @top:  is this a top grammar
7819  *
7820  * Dump a RelaxNG structure back
7821  */
7822 static void
7823 xmlRelaxNGDumpGrammar(FILE * output, xmlRelaxNGGrammarPtr grammar, int top)
7824 {
7825     if (grammar == NULL)
7826         return;
7827
7828     fprintf(output, "<grammar");
7829     if (top)
7830         fprintf(output, " xmlns=\"http://relaxng.org/ns/structure/1.0\"");
7831     switch (grammar->combine) {
7832         case XML_RELAXNG_COMBINE_UNDEFINED:
7833             break;
7834         case XML_RELAXNG_COMBINE_CHOICE:
7835             fprintf(output, " combine=\"choice\"");
7836             break;
7837         case XML_RELAXNG_COMBINE_INTERLEAVE:
7838             fprintf(output, " combine=\"interleave\"");
7839             break;
7840         default:
7841             fprintf(output, " <!-- invalid combine value -->");
7842     }
7843     fprintf(output, ">\n");
7844     if (grammar->start == NULL) {
7845         fprintf(output, " <!-- grammar had no start -->");
7846     } else {
7847         fprintf(output, "<start>\n");
7848         xmlRelaxNGDumpDefine(output, grammar->start);
7849         fprintf(output, "</start>\n");
7850     }
7851     /* TODO ? Dump the defines ? */
7852     fprintf(output, "</grammar>\n");
7853 }
7854
7855 /**
7856  * xmlRelaxNGDump:
7857  * @output:  the file output
7858  * @schema:  a schema structure
7859  *
7860  * Dump a RelaxNG structure back
7861  */
7862 void
7863 xmlRelaxNGDump(FILE * output, xmlRelaxNGPtr schema)
7864 {
7865     if (output == NULL)
7866         return;
7867     if (schema == NULL) {
7868         fprintf(output, "RelaxNG empty or failed to compile\n");
7869         return;
7870     }
7871     fprintf(output, "RelaxNG: ");
7872     if (schema->doc == NULL) {
7873         fprintf(output, "no document\n");
7874     } else if (schema->doc->URL != NULL) {
7875         fprintf(output, "%s\n", schema->doc->URL);
7876     } else {
7877         fprintf(output, "\n");
7878     }
7879     if (schema->topgrammar == NULL) {
7880         fprintf(output, "RelaxNG has no top grammar\n");
7881         return;
7882     }
7883     xmlRelaxNGDumpGrammar(output, schema->topgrammar, 1);
7884 }
7885
7886 /**
7887  * xmlRelaxNGDumpTree:
7888  * @output:  the file output
7889  * @schema:  a schema structure
7890  *
7891  * Dump the transformed RelaxNG tree.
7892  */
7893 void
7894 xmlRelaxNGDumpTree(FILE * output, xmlRelaxNGPtr schema)
7895 {
7896     if (output == NULL)
7897         return;
7898     if (schema == NULL) {
7899         fprintf(output, "RelaxNG empty or failed to compile\n");
7900         return;
7901     }
7902     if (schema->doc == NULL) {
7903         fprintf(output, "no document\n");
7904     } else {
7905         xmlDocDump(output, schema->doc);
7906     }
7907 }
7908 #endif /* LIBXML_OUTPUT_ENABLED */
7909
7910 /************************************************************************
7911  *                                                                      *
7912  *              Validation of compiled content                          *
7913  *                                                                      *
7914  ************************************************************************/
7915 static int xmlRelaxNGValidateDefinition(xmlRelaxNGValidCtxtPtr ctxt,
7916                                         xmlRelaxNGDefinePtr define);
7917
7918 /**
7919  * xmlRelaxNGValidateCompiledCallback:
7920  * @exec:  the regular expression instance
7921  * @token:  the token which matched
7922  * @transdata:  callback data, the define for the subelement if available
7923  @ @inputdata:  callback data, the Relax NG validation context
7924  *
7925  * Handle the callback and if needed validate the element children.
7926  */
7927 static void
7928 xmlRelaxNGValidateCompiledCallback(xmlRegExecCtxtPtr exec ATTRIBUTE_UNUSED,
7929                                    const xmlChar * token,
7930                                    void *transdata, void *inputdata)
7931 {
7932     xmlRelaxNGValidCtxtPtr ctxt = (xmlRelaxNGValidCtxtPtr) inputdata;
7933     xmlRelaxNGDefinePtr define = (xmlRelaxNGDefinePtr) transdata;
7934     int ret;
7935
7936 #ifdef DEBUG_COMPILE
7937     xmlGenericError(xmlGenericErrorContext,
7938                     "Compiled callback for: '%s'\n", token);
7939 #endif
7940     if (ctxt == NULL) {
7941         fprintf(stderr, "callback on %s missing context\n", token);
7942         return;
7943     }
7944     if (define == NULL) {
7945         if (token[0] == '#')
7946             return;
7947         fprintf(stderr, "callback on %s missing define\n", token);
7948         if ((ctxt != NULL) && (ctxt->errNo == XML_RELAXNG_OK))
7949             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
7950         return;
7951     }
7952     if ((ctxt == NULL) || (define == NULL)) {
7953         fprintf(stderr, "callback on %s missing info\n", token);
7954         if ((ctxt != NULL) && (ctxt->errNo == XML_RELAXNG_OK))
7955             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
7956         return;
7957     } else if (define->type != XML_RELAXNG_ELEMENT) {
7958         fprintf(stderr, "callback on %s define is not element\n", token);
7959         if (ctxt->errNo == XML_RELAXNG_OK)
7960             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
7961         return;
7962     }
7963     ret = xmlRelaxNGValidateDefinition(ctxt, define);
7964     if (ret != 0)
7965         ctxt->perr = ret;
7966 }
7967
7968 /**
7969  * xmlRelaxNGValidateCompiledContent:
7970  * @ctxt:  the RelaxNG validation context
7971  * @regexp:  the regular expression as compiled
7972  * @content:  list of children to test against the regexp
7973  *
7974  * Validate the content model of an element or start using the regexp
7975  *
7976  * Returns 0 in case of success, -1 in case of error.
7977  */
7978 static int
7979 xmlRelaxNGValidateCompiledContent(xmlRelaxNGValidCtxtPtr ctxt,
7980                                   xmlRegexpPtr regexp, xmlNodePtr content)
7981 {
7982     xmlRegExecCtxtPtr exec;
7983     xmlNodePtr cur;
7984     int ret = 0;
7985     int oldperr;
7986
7987     if ((ctxt == NULL) || (regexp == NULL))
7988         return (-1);
7989     oldperr = ctxt->perr;
7990     exec = xmlRegNewExecCtxt(regexp,
7991                              xmlRelaxNGValidateCompiledCallback, ctxt);
7992     ctxt->perr = 0;
7993     cur = content;
7994     while (cur != NULL) {
7995         ctxt->state->seq = cur;
7996         switch (cur->type) {
7997             case XML_TEXT_NODE:
7998             case XML_CDATA_SECTION_NODE:
7999                 if (xmlIsBlankNode(cur))
8000                     break;
8001                 ret = xmlRegExecPushString(exec, BAD_CAST "#text", ctxt);
8002                 if (ret < 0) {
8003                     VALID_ERR2(XML_RELAXNG_ERR_TEXTWRONG,
8004                                cur->parent->name);
8005                 }
8006                 break;
8007             case XML_ELEMENT_NODE:
8008                 if (cur->ns != NULL) {
8009                     ret = xmlRegExecPushString2(exec, cur->name,
8010                                                 cur->ns->href, ctxt);
8011                 } else {
8012                     ret = xmlRegExecPushString(exec, cur->name, ctxt);
8013                 }
8014                 if (ret < 0) {
8015                     VALID_ERR2(XML_RELAXNG_ERR_ELEMWRONG, cur->name);
8016                 }
8017                 break;
8018             default:
8019                 break;
8020         }
8021         if (ret < 0)
8022             break;
8023         /*
8024          * Switch to next element
8025          */
8026         cur = cur->next;
8027     }
8028     ret = xmlRegExecPushString(exec, NULL, NULL);
8029     if (ret == 1) {
8030         ret = 0;
8031         ctxt->state->seq = NULL;
8032     } else if (ret == 0) {
8033         /*
8034          * TODO: get some of the names needed to exit the current state of exec
8035          */
8036         VALID_ERR2(XML_RELAXNG_ERR_NOELEM, BAD_CAST "");
8037         ret = -1;
8038         if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
8039             xmlRelaxNGDumpValidError(ctxt);
8040     } else {
8041         ret = -1;
8042     }
8043     xmlRegFreeExecCtxt(exec);
8044     /*
8045      * There might be content model errors outside of the pure
8046      * regexp validation, e.g. for attribute values.
8047      */
8048     if ((ret == 0) && (ctxt->perr != 0)) {
8049         ret = ctxt->perr;
8050     }
8051     ctxt->perr = oldperr;
8052     return (ret);
8053 }
8054
8055 /************************************************************************
8056  *                                                                      *
8057  *              Progressive validation of when possible                 *
8058  *                                                                      *
8059  ************************************************************************/
8060 static int xmlRelaxNGValidateAttributeList(xmlRelaxNGValidCtxtPtr ctxt,
8061                                            xmlRelaxNGDefinePtr defines);
8062 static int xmlRelaxNGValidateElementEnd(xmlRelaxNGValidCtxtPtr ctxt,
8063                                         int dolog);
8064 static void xmlRelaxNGLogBestError(xmlRelaxNGValidCtxtPtr ctxt);
8065
8066 /**
8067  * xmlRelaxNGElemPush:
8068  * @ctxt:  the validation context
8069  * @exec:  the regexp runtime for the new content model
8070  *
8071  * Push a new regexp for the current node content model on the stack
8072  *
8073  * Returns 0 in case of success and -1 in case of error.
8074  */
8075 static int
8076 xmlRelaxNGElemPush(xmlRelaxNGValidCtxtPtr ctxt, xmlRegExecCtxtPtr exec)
8077 {
8078     if (ctxt->elemTab == NULL) {
8079         ctxt->elemMax = 10;
8080         ctxt->elemTab = (xmlRegExecCtxtPtr *) xmlMalloc(ctxt->elemMax *
8081                                                         sizeof
8082                                                         (xmlRegExecCtxtPtr));
8083         if (ctxt->elemTab == NULL) {
8084             xmlRngVErrMemory(ctxt, "validating\n");
8085             return (-1);
8086         }
8087     }
8088     if (ctxt->elemNr >= ctxt->elemMax) {
8089         ctxt->elemMax *= 2;
8090         ctxt->elemTab = (xmlRegExecCtxtPtr *) xmlRealloc(ctxt->elemTab,
8091                                                          ctxt->elemMax *
8092                                                          sizeof
8093                                                          (xmlRegExecCtxtPtr));
8094         if (ctxt->elemTab == NULL) {
8095             xmlRngVErrMemory(ctxt, "validating\n");
8096             return (-1);
8097         }
8098     }
8099     ctxt->elemTab[ctxt->elemNr++] = exec;
8100     ctxt->elem = exec;
8101     return (0);
8102 }
8103
8104 /**
8105  * xmlRelaxNGElemPop:
8106  * @ctxt:  the validation context
8107  *
8108  * Pop the regexp of the current node content model from the stack
8109  *
8110  * Returns the exec or NULL if empty
8111  */
8112 static xmlRegExecCtxtPtr
8113 xmlRelaxNGElemPop(xmlRelaxNGValidCtxtPtr ctxt)
8114 {
8115     xmlRegExecCtxtPtr ret;
8116
8117     if (ctxt->elemNr <= 0)
8118         return (NULL);
8119     ctxt->elemNr--;
8120     ret = ctxt->elemTab[ctxt->elemNr];
8121     ctxt->elemTab[ctxt->elemNr] = NULL;
8122     if (ctxt->elemNr > 0)
8123         ctxt->elem = ctxt->elemTab[ctxt->elemNr - 1];
8124     else
8125         ctxt->elem = NULL;
8126     return (ret);
8127 }
8128
8129 /**
8130  * xmlRelaxNGValidateProgressiveCallback:
8131  * @exec:  the regular expression instance
8132  * @token:  the token which matched
8133  * @transdata:  callback data, the define for the subelement if available
8134  @ @inputdata:  callback data, the Relax NG validation context
8135  *
8136  * Handle the callback and if needed validate the element children.
8137  * some of the in/out informations are passed via the context in @inputdata.
8138  */
8139 static void
8140 xmlRelaxNGValidateProgressiveCallback(xmlRegExecCtxtPtr exec
8141                                       ATTRIBUTE_UNUSED,
8142                                       const xmlChar * token,
8143                                       void *transdata, void *inputdata)
8144 {
8145     xmlRelaxNGValidCtxtPtr ctxt = (xmlRelaxNGValidCtxtPtr) inputdata;
8146     xmlRelaxNGDefinePtr define = (xmlRelaxNGDefinePtr) transdata;
8147     xmlRelaxNGValidStatePtr state, oldstate;
8148     xmlNodePtr node;
8149     int ret = 0, oldflags;
8150
8151 #ifdef DEBUG_PROGRESSIVE
8152     xmlGenericError(xmlGenericErrorContext,
8153                     "Progressive callback for: '%s'\n", token);
8154 #endif
8155     if (ctxt == NULL) {
8156         fprintf(stderr, "callback on %s missing context\n", token);
8157         return;
8158     }
8159     node = ctxt->pnode;
8160     ctxt->pstate = 1;
8161     if (define == NULL) {
8162         if (token[0] == '#')
8163             return;
8164         fprintf(stderr, "callback on %s missing define\n", token);
8165         if ((ctxt != NULL) && (ctxt->errNo == XML_RELAXNG_OK))
8166             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
8167         ctxt->pstate = -1;
8168         return;
8169     }
8170     if ((ctxt == NULL) || (define == NULL)) {
8171         fprintf(stderr, "callback on %s missing info\n", token);
8172         if ((ctxt != NULL) && (ctxt->errNo == XML_RELAXNG_OK))
8173             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
8174         ctxt->pstate = -1;
8175         return;
8176     } else if (define->type != XML_RELAXNG_ELEMENT) {
8177         fprintf(stderr, "callback on %s define is not element\n", token);
8178         if (ctxt->errNo == XML_RELAXNG_OK)
8179             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
8180         ctxt->pstate = -1;
8181         return;
8182     }
8183     if (node->type != XML_ELEMENT_NODE) {
8184         VALID_ERR(XML_RELAXNG_ERR_NOTELEM);
8185         if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
8186             xmlRelaxNGDumpValidError(ctxt);
8187         ctxt->pstate = -1;
8188         return;
8189     }
8190     if (define->contModel == NULL) {
8191         /*
8192          * this node cannot be validated in a streamable fashion
8193          */
8194 #ifdef DEBUG_PROGRESSIVE
8195         xmlGenericError(xmlGenericErrorContext,
8196                         "Element '%s' validation is not streamable\n",
8197                         token);
8198 #endif
8199         ctxt->pstate = 0;
8200         ctxt->pdef = define;
8201         return;
8202     }
8203     exec = xmlRegNewExecCtxt(define->contModel,
8204                              xmlRelaxNGValidateProgressiveCallback, ctxt);
8205     if (exec == NULL) {
8206         ctxt->pstate = -1;
8207         return;
8208     }
8209     xmlRelaxNGElemPush(ctxt, exec);
8210
8211     /*
8212      * Validate the attributes part of the content.
8213      */
8214     state = xmlRelaxNGNewValidState(ctxt, node);
8215     if (state == NULL) {
8216         ctxt->pstate = -1;
8217         return;
8218     }
8219     oldstate = ctxt->state;
8220     ctxt->state = state;
8221     if (define->attrs != NULL) {
8222         ret = xmlRelaxNGValidateAttributeList(ctxt, define->attrs);
8223         if (ret != 0) {
8224             ctxt->pstate = -1;
8225             VALID_ERR2(XML_RELAXNG_ERR_ATTRVALID, node->name);
8226         }
8227     }
8228     if (ctxt->state != NULL) {
8229         ctxt->state->seq = NULL;
8230         ret = xmlRelaxNGValidateElementEnd(ctxt, 1);
8231         if (ret != 0) {
8232             ctxt->pstate = -1;
8233         }
8234         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
8235     } else if (ctxt->states != NULL) {
8236         int tmp = -1, i;
8237
8238         oldflags = ctxt->flags;
8239
8240         for (i = 0; i < ctxt->states->nbState; i++) {
8241             state = ctxt->states->tabState[i];
8242             ctxt->state = state;
8243             ctxt->state->seq = NULL;
8244
8245             if (xmlRelaxNGValidateElementEnd(ctxt, 0) == 0) {
8246                 tmp = 0;
8247                 break;
8248             }
8249         }
8250         if (tmp != 0) {
8251             /*
8252              * validation error, log the message for the "best" one
8253              */
8254             ctxt->flags |= FLAGS_IGNORABLE;
8255             xmlRelaxNGLogBestError(ctxt);
8256         }
8257         for (i = 0; i < ctxt->states->nbState; i++) {
8258             xmlRelaxNGFreeValidState(ctxt, ctxt->states->tabState[i]);
8259         }
8260         xmlRelaxNGFreeStates(ctxt, ctxt->states);
8261         ctxt->states = NULL;
8262         if ((ret == 0) && (tmp == -1))
8263             ctxt->pstate = -1;
8264         ctxt->flags = oldflags;
8265     }
8266     if (ctxt->pstate == -1) {
8267         if ((ctxt->flags & FLAGS_IGNORABLE) == 0) {
8268             xmlRelaxNGDumpValidError(ctxt);
8269         }
8270     }
8271     ctxt->state = oldstate;
8272 }
8273
8274 /**
8275  * xmlRelaxNGValidatePushElement:
8276  * @ctxt:  the validation context
8277  * @doc:  a document instance
8278  * @elem:  an element instance
8279  *
8280  * Push a new element start on the RelaxNG validation stack.
8281  *
8282  * returns 1 if no validation problem was found or 0 if validating the
8283  *         element requires a full node, and -1 in case of error.
8284  */
8285 int
8286 xmlRelaxNGValidatePushElement(xmlRelaxNGValidCtxtPtr ctxt,
8287                               xmlDocPtr doc ATTRIBUTE_UNUSED,
8288                               xmlNodePtr elem)
8289 {
8290     int ret = 1;
8291
8292     if ((ctxt == NULL) || (elem == NULL))
8293         return (-1);
8294
8295 #ifdef DEBUG_PROGRESSIVE
8296     xmlGenericError(xmlGenericErrorContext, "PushElem %s\n", elem->name);
8297 #endif
8298     if (ctxt->elem == 0) {
8299         xmlRelaxNGPtr schema;
8300         xmlRelaxNGGrammarPtr grammar;
8301         xmlRegExecCtxtPtr exec;
8302         xmlRelaxNGDefinePtr define;
8303
8304         schema = ctxt->schema;
8305         if (schema == NULL) {
8306             VALID_ERR(XML_RELAXNG_ERR_NOGRAMMAR);
8307             return (-1);
8308         }
8309         grammar = schema->topgrammar;
8310         if ((grammar == NULL) || (grammar->start == NULL)) {
8311             VALID_ERR(XML_RELAXNG_ERR_NOGRAMMAR);
8312             return (-1);
8313         }
8314         define = grammar->start;
8315         if (define->contModel == NULL) {
8316             ctxt->pdef = define;
8317             return (0);
8318         }
8319         exec = xmlRegNewExecCtxt(define->contModel,
8320                                  xmlRelaxNGValidateProgressiveCallback,
8321                                  ctxt);
8322         if (exec == NULL) {
8323             return (-1);
8324         }
8325         xmlRelaxNGElemPush(ctxt, exec);
8326     }
8327     ctxt->pnode = elem;
8328     ctxt->pstate = 0;
8329     if (elem->ns != NULL) {
8330         ret =
8331             xmlRegExecPushString2(ctxt->elem, elem->name, elem->ns->href,
8332                                   ctxt);
8333     } else {
8334         ret = xmlRegExecPushString(ctxt->elem, elem->name, ctxt);
8335     }
8336     if (ret < 0) {
8337         VALID_ERR2(XML_RELAXNG_ERR_ELEMWRONG, elem->name);
8338     } else {
8339         if (ctxt->pstate == 0)
8340             ret = 0;
8341         else if (ctxt->pstate < 0)
8342             ret = -1;
8343         else
8344             ret = 1;
8345     }
8346 #ifdef DEBUG_PROGRESSIVE
8347     if (ret < 0)
8348         xmlGenericError(xmlGenericErrorContext, "PushElem %s failed\n",
8349                         elem->name);
8350 #endif
8351     return (ret);
8352 }
8353
8354 /**
8355  * xmlRelaxNGValidatePushCData:
8356  * @ctxt:  the RelaxNG validation context
8357  * @data:  some character data read
8358  * @len:  the length of the data
8359  *
8360  * check the CData parsed for validation in the current stack
8361  *
8362  * returns 1 if no validation problem was found or -1 otherwise
8363  */
8364 int
8365 xmlRelaxNGValidatePushCData(xmlRelaxNGValidCtxtPtr ctxt,
8366                             const xmlChar * data, int len ATTRIBUTE_UNUSED)
8367 {
8368     int ret = 1;
8369
8370     if ((ctxt == NULL) || (ctxt->elem == NULL) || (data == NULL))
8371         return (-1);
8372
8373 #ifdef DEBUG_PROGRESSIVE
8374     xmlGenericError(xmlGenericErrorContext, "CDATA %s %d\n", data, len);
8375 #endif
8376
8377     while (*data != 0) {
8378         if (!IS_BLANK_CH(*data))
8379             break;
8380         data++;
8381     }
8382     if (*data == 0)
8383         return (1);
8384
8385     ret = xmlRegExecPushString(ctxt->elem, BAD_CAST "#text", ctxt);
8386     if (ret < 0) {
8387         VALID_ERR2(XML_RELAXNG_ERR_TEXTWRONG, BAD_CAST " TODO ");
8388 #ifdef DEBUG_PROGRESSIVE
8389         xmlGenericError(xmlGenericErrorContext, "CDATA failed\n");
8390 #endif
8391
8392         return (-1);
8393     }
8394     return (1);
8395 }
8396
8397 /**
8398  * xmlRelaxNGValidatePopElement:
8399  * @ctxt:  the RelaxNG validation context
8400  * @doc:  a document instance
8401  * @elem:  an element instance
8402  *
8403  * Pop the element end from the RelaxNG validation stack.
8404  *
8405  * returns 1 if no validation problem was found or 0 otherwise
8406  */
8407 int
8408 xmlRelaxNGValidatePopElement(xmlRelaxNGValidCtxtPtr ctxt,
8409                              xmlDocPtr doc ATTRIBUTE_UNUSED,
8410                              xmlNodePtr elem)
8411 {
8412     int ret;
8413     xmlRegExecCtxtPtr exec;
8414
8415     if ((ctxt == NULL) || (ctxt->elem == NULL) || (elem == NULL))
8416         return (-1);
8417 #ifdef DEBUG_PROGRESSIVE
8418     xmlGenericError(xmlGenericErrorContext, "PopElem %s\n", elem->name);
8419 #endif
8420     /*
8421      * verify that we reached a terminal state of the content model.
8422      */
8423     exec = xmlRelaxNGElemPop(ctxt);
8424     ret = xmlRegExecPushString(exec, NULL, NULL);
8425     if (ret == 0) {
8426         /*
8427          * TODO: get some of the names needed to exit the current state of exec
8428          */
8429         VALID_ERR2(XML_RELAXNG_ERR_NOELEM, BAD_CAST "");
8430         ret = -1;
8431     } else if (ret < 0) {
8432         ret = -1;
8433     } else {
8434         ret = 1;
8435     }
8436     xmlRegFreeExecCtxt(exec);
8437 #ifdef DEBUG_PROGRESSIVE
8438     if (ret < 0)
8439         xmlGenericError(xmlGenericErrorContext, "PopElem %s failed\n",
8440                         elem->name);
8441 #endif
8442     return (ret);
8443 }
8444
8445 /**
8446  * xmlRelaxNGValidateFullElement:
8447  * @ctxt:  the validation context
8448  * @doc:  a document instance
8449  * @elem:  an element instance
8450  *
8451  * Validate a full subtree when xmlRelaxNGValidatePushElement() returned
8452  * 0 and the content of the node has been expanded.
8453  *
8454  * returns 1 if no validation problem was found or -1 in case of error.
8455  */
8456 int
8457 xmlRelaxNGValidateFullElement(xmlRelaxNGValidCtxtPtr ctxt,
8458                               xmlDocPtr doc ATTRIBUTE_UNUSED,
8459                               xmlNodePtr elem)
8460 {
8461     int ret;
8462     xmlRelaxNGValidStatePtr state;
8463
8464     if ((ctxt == NULL) || (ctxt->pdef == NULL) || (elem == NULL))
8465         return (-1);
8466 #ifdef DEBUG_PROGRESSIVE
8467     xmlGenericError(xmlGenericErrorContext, "FullElem %s\n", elem->name);
8468 #endif
8469     state = xmlRelaxNGNewValidState(ctxt, elem->parent);
8470     if (state == NULL) {
8471         return (-1);
8472     }
8473     state->seq = elem;
8474     ctxt->state = state;
8475     ctxt->errNo = XML_RELAXNG_OK;
8476     ret = xmlRelaxNGValidateDefinition(ctxt, ctxt->pdef);
8477     if ((ret != 0) || (ctxt->errNo != XML_RELAXNG_OK))
8478         ret = -1;
8479     else
8480         ret = 1;
8481     xmlRelaxNGFreeValidState(ctxt, ctxt->state);
8482     ctxt->state = NULL;
8483 #ifdef DEBUG_PROGRESSIVE
8484     if (ret < 0)
8485         xmlGenericError(xmlGenericErrorContext, "FullElem %s failed\n",
8486                         elem->name);
8487 #endif
8488     return (ret);
8489 }
8490
8491 /************************************************************************
8492  *                                                                      *
8493  *              Generic interpreted validation implementation           *
8494  *                                                                      *
8495  ************************************************************************/
8496 static int xmlRelaxNGValidateValue(xmlRelaxNGValidCtxtPtr ctxt,
8497                                    xmlRelaxNGDefinePtr define);
8498
8499 /**
8500  * xmlRelaxNGSkipIgnored:
8501  * @ctxt:  a schema validation context
8502  * @node:  the top node.
8503  *
8504  * Skip ignorable nodes in that context
8505  *
8506  * Returns the new sibling or NULL in case of error.
8507  */
8508 static xmlNodePtr
8509 xmlRelaxNGSkipIgnored(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
8510                       xmlNodePtr node)
8511 {
8512     /*
8513      * TODO complete and handle entities
8514      */
8515     while ((node != NULL) &&
8516            ((node->type == XML_COMMENT_NODE) ||
8517             (node->type == XML_PI_NODE) ||
8518             (node->type == XML_XINCLUDE_START) ||
8519             (node->type == XML_XINCLUDE_END) ||
8520             (((node->type == XML_TEXT_NODE) ||
8521               (node->type == XML_CDATA_SECTION_NODE)) &&
8522              ((ctxt->flags & FLAGS_MIXED_CONTENT) ||
8523               (IS_BLANK_NODE(node)))))) {
8524         node = node->next;
8525     }
8526     return (node);
8527 }
8528
8529 /**
8530  * xmlRelaxNGNormalize:
8531  * @ctxt:  a schema validation context
8532  * @str:  the string to normalize
8533  *
8534  * Implements the  normalizeWhiteSpace( s ) function from
8535  * section 6.2.9 of the spec
8536  *
8537  * Returns the new string or NULL in case of error.
8538  */
8539 static xmlChar *
8540 xmlRelaxNGNormalize(xmlRelaxNGValidCtxtPtr ctxt, const xmlChar * str)
8541 {
8542     xmlChar *ret, *p;
8543     const xmlChar *tmp;
8544     int len;
8545
8546     if (str == NULL)
8547         return (NULL);
8548     tmp = str;
8549     while (*tmp != 0)
8550         tmp++;
8551     len = tmp - str;
8552
8553     ret = (xmlChar *) xmlMallocAtomic((len + 1) * sizeof(xmlChar));
8554     if (ret == NULL) {
8555         xmlRngVErrMemory(ctxt, "validating\n");
8556         return (NULL);
8557     }
8558     p = ret;
8559     while (IS_BLANK_CH(*str))
8560         str++;
8561     while (*str != 0) {
8562         if (IS_BLANK_CH(*str)) {
8563             while (IS_BLANK_CH(*str))
8564                 str++;
8565             if (*str == 0)
8566                 break;
8567             *p++ = ' ';
8568         } else
8569             *p++ = *str++;
8570     }
8571     *p = 0;
8572     return (ret);
8573 }
8574
8575 /**
8576  * xmlRelaxNGValidateDatatype:
8577  * @ctxt:  a Relax-NG validation context
8578  * @value:  the string value
8579  * @type:  the datatype definition
8580  * @node:  the node
8581  *
8582  * Validate the given value against the dataype
8583  *
8584  * Returns 0 if the validation succeeded or an error code.
8585  */
8586 static int
8587 xmlRelaxNGValidateDatatype(xmlRelaxNGValidCtxtPtr ctxt,
8588                            const xmlChar * value,
8589                            xmlRelaxNGDefinePtr define, xmlNodePtr node)
8590 {
8591     int ret, tmp;
8592     xmlRelaxNGTypeLibraryPtr lib;
8593     void *result = NULL;
8594     xmlRelaxNGDefinePtr cur;
8595
8596     if ((define == NULL) || (define->data == NULL)) {
8597         return (-1);
8598     }
8599     lib = (xmlRelaxNGTypeLibraryPtr) define->data;
8600     if (lib->check != NULL) {
8601         if ((define->attrs != NULL) &&
8602             (define->attrs->type == XML_RELAXNG_PARAM)) {
8603             ret =
8604                 lib->check(lib->data, define->name, value, &result, node);
8605         } else {
8606             ret = lib->check(lib->data, define->name, value, NULL, node);
8607         }
8608     } else
8609         ret = -1;
8610     if (ret < 0) {
8611         VALID_ERR2(XML_RELAXNG_ERR_TYPE, define->name);
8612         if ((result != NULL) && (lib != NULL) && (lib->freef != NULL))
8613             lib->freef(lib->data, result);
8614         return (-1);
8615     } else if (ret == 1) {
8616         ret = 0;
8617     } else if (ret == 2) {
8618         VALID_ERR2P(XML_RELAXNG_ERR_DUPID, value);
8619     } else {
8620         VALID_ERR3P(XML_RELAXNG_ERR_TYPEVAL, define->name, value);
8621         ret = -1;
8622     }
8623     cur = define->attrs;
8624     while ((ret == 0) && (cur != NULL) && (cur->type == XML_RELAXNG_PARAM)) {
8625         if (lib->facet != NULL) {
8626             tmp = lib->facet(lib->data, define->name, cur->name,
8627                              cur->value, value, result);
8628             if (tmp != 0)
8629                 ret = -1;
8630         }
8631         cur = cur->next;
8632     }
8633     if ((ret == 0) && (define->content != NULL)) {
8634         const xmlChar *oldvalue, *oldendvalue;
8635
8636         oldvalue = ctxt->state->value;
8637         oldendvalue = ctxt->state->endvalue;
8638         ctxt->state->value = (xmlChar *) value;
8639         ctxt->state->endvalue = NULL;
8640         ret = xmlRelaxNGValidateValue(ctxt, define->content);
8641         ctxt->state->value = (xmlChar *) oldvalue;
8642         ctxt->state->endvalue = (xmlChar *) oldendvalue;
8643     }
8644     if ((result != NULL) && (lib != NULL) && (lib->freef != NULL))
8645         lib->freef(lib->data, result);
8646     return (ret);
8647 }
8648
8649 /**
8650  * xmlRelaxNGNextValue:
8651  * @ctxt:  a Relax-NG validation context
8652  *
8653  * Skip to the next value when validating within a list
8654  *
8655  * Returns 0 if the operation succeeded or an error code.
8656  */
8657 static int
8658 xmlRelaxNGNextValue(xmlRelaxNGValidCtxtPtr ctxt)
8659 {
8660     xmlChar *cur;
8661
8662     cur = ctxt->state->value;
8663     if ((cur == NULL) || (ctxt->state->endvalue == NULL)) {
8664         ctxt->state->value = NULL;
8665         ctxt->state->endvalue = NULL;
8666         return (0);
8667     }
8668     while (*cur != 0)
8669         cur++;
8670     while ((cur != ctxt->state->endvalue) && (*cur == 0))
8671         cur++;
8672     if (cur == ctxt->state->endvalue)
8673         ctxt->state->value = NULL;
8674     else
8675         ctxt->state->value = cur;
8676     return (0);
8677 }
8678
8679 /**
8680  * xmlRelaxNGValidateValueList:
8681  * @ctxt:  a Relax-NG validation context
8682  * @defines:  the list of definitions to verify
8683  *
8684  * Validate the given set of definitions for the current value
8685  *
8686  * Returns 0 if the validation succeeded or an error code.
8687  */
8688 static int
8689 xmlRelaxNGValidateValueList(xmlRelaxNGValidCtxtPtr ctxt,
8690                             xmlRelaxNGDefinePtr defines)
8691 {
8692     int ret = 0;
8693
8694     while (defines != NULL) {
8695         ret = xmlRelaxNGValidateValue(ctxt, defines);
8696         if (ret != 0)
8697             break;
8698         defines = defines->next;
8699     }
8700     return (ret);
8701 }
8702
8703 /**
8704  * xmlRelaxNGValidateValue:
8705  * @ctxt:  a Relax-NG validation context
8706  * @define:  the definition to verify
8707  *
8708  * Validate the given definition for the current value
8709  *
8710  * Returns 0 if the validation succeeded or an error code.
8711  */
8712 static int
8713 xmlRelaxNGValidateValue(xmlRelaxNGValidCtxtPtr ctxt,
8714                         xmlRelaxNGDefinePtr define)
8715 {
8716     int ret = 0, oldflags;
8717     xmlChar *value;
8718
8719     value = ctxt->state->value;
8720     switch (define->type) {
8721         case XML_RELAXNG_EMPTY:{
8722                 if ((value != NULL) && (value[0] != 0)) {
8723                     int idx = 0;
8724
8725                     while (IS_BLANK_CH(value[idx]))
8726                         idx++;
8727                     if (value[idx] != 0)
8728                         ret = -1;
8729                 }
8730                 break;
8731             }
8732         case XML_RELAXNG_TEXT:
8733             break;
8734         case XML_RELAXNG_VALUE:{
8735                 if (!xmlStrEqual(value, define->value)) {
8736                     if (define->name != NULL) {
8737                         xmlRelaxNGTypeLibraryPtr lib;
8738
8739                         lib = (xmlRelaxNGTypeLibraryPtr) define->data;
8740                         if ((lib != NULL) && (lib->comp != NULL)) {
8741                             ret = lib->comp(lib->data, define->name,
8742                                             define->value, define->node,
8743                                             (void *) define->attrs,
8744                                             value, ctxt->state->node);
8745                         } else
8746                             ret = -1;
8747                         if (ret < 0) {
8748                             VALID_ERR2(XML_RELAXNG_ERR_TYPECMP,
8749                                        define->name);
8750                             return (-1);
8751                         } else if (ret == 1) {
8752                             ret = 0;
8753                         } else {
8754                             ret = -1;
8755                         }
8756                     } else {
8757                         xmlChar *nval, *nvalue;
8758
8759                         /*
8760                          * TODO: trivial optimizations are possible by
8761                          * computing at compile-time
8762                          */
8763                         nval = xmlRelaxNGNormalize(ctxt, define->value);
8764                         nvalue = xmlRelaxNGNormalize(ctxt, value);
8765
8766                         if ((nval == NULL) || (nvalue == NULL) ||
8767                             (!xmlStrEqual(nval, nvalue)))
8768                             ret = -1;
8769                         if (nval != NULL)
8770                             xmlFree(nval);
8771                         if (nvalue != NULL)
8772                             xmlFree(nvalue);
8773                     }
8774                 }
8775                 if (ret == 0)
8776                     xmlRelaxNGNextValue(ctxt);
8777                 break;
8778             }
8779         case XML_RELAXNG_DATATYPE:{
8780                 ret = xmlRelaxNGValidateDatatype(ctxt, value, define,
8781                                                  ctxt->state->seq);
8782                 if (ret == 0)
8783                     xmlRelaxNGNextValue(ctxt);
8784
8785                 break;
8786             }
8787         case XML_RELAXNG_CHOICE:{
8788                 xmlRelaxNGDefinePtr list = define->content;
8789                 xmlChar *oldvalue;
8790
8791                 oldflags = ctxt->flags;
8792                 ctxt->flags |= FLAGS_IGNORABLE;
8793
8794                 oldvalue = ctxt->state->value;
8795                 while (list != NULL) {
8796                     ret = xmlRelaxNGValidateValue(ctxt, list);
8797                     if (ret == 0) {
8798                         break;
8799                     }
8800                     ctxt->state->value = oldvalue;
8801                     list = list->next;
8802                 }
8803                 ctxt->flags = oldflags;
8804                 if (ret != 0) {
8805                     if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
8806                         xmlRelaxNGDumpValidError(ctxt);
8807                 } else {
8808                     if (ctxt->errNr > 0)
8809                         xmlRelaxNGPopErrors(ctxt, 0);
8810                 }
8811                 break;
8812             }
8813         case XML_RELAXNG_LIST:{
8814                 xmlRelaxNGDefinePtr list = define->content;
8815                 xmlChar *oldvalue, *oldend, *val, *cur;
8816
8817 #ifdef DEBUG_LIST
8818                 int nb_values = 0;
8819 #endif
8820
8821                 oldvalue = ctxt->state->value;
8822                 oldend = ctxt->state->endvalue;
8823
8824                 val = xmlStrdup(oldvalue);
8825                 if (val == NULL) {
8826                     val = xmlStrdup(BAD_CAST "");
8827                 }
8828                 if (val == NULL) {
8829                     VALID_ERR(XML_RELAXNG_ERR_NOSTATE);
8830                     return (-1);
8831                 }
8832                 cur = val;
8833                 while (*cur != 0) {
8834                     if (IS_BLANK_CH(*cur)) {
8835                         *cur = 0;
8836                         cur++;
8837 #ifdef DEBUG_LIST
8838                         nb_values++;
8839 #endif
8840                         while (IS_BLANK_CH(*cur))
8841                             *cur++ = 0;
8842                     } else
8843                         cur++;
8844                 }
8845 #ifdef DEBUG_LIST
8846                 xmlGenericError(xmlGenericErrorContext,
8847                                 "list value: '%s' found %d items\n",
8848                                 oldvalue, nb_values);
8849                 nb_values = 0;
8850 #endif
8851                 ctxt->state->endvalue = cur;
8852                 cur = val;
8853                 while ((*cur == 0) && (cur != ctxt->state->endvalue))
8854                     cur++;
8855
8856                 ctxt->state->value = cur;
8857
8858                 while (list != NULL) {
8859                     if (ctxt->state->value == ctxt->state->endvalue)
8860                         ctxt->state->value = NULL;
8861                     ret = xmlRelaxNGValidateValue(ctxt, list);
8862                     if (ret != 0) {
8863 #ifdef DEBUG_LIST
8864                         xmlGenericError(xmlGenericErrorContext,
8865                                         "Failed to validate value: '%s' with %d rule\n",
8866                                         ctxt->state->value, nb_values);
8867 #endif
8868                         break;
8869                     }
8870 #ifdef DEBUG_LIST
8871                     nb_values++;
8872 #endif
8873                     list = list->next;
8874                 }
8875
8876                 if ((ret == 0) && (ctxt->state->value != NULL) &&
8877                     (ctxt->state->value != ctxt->state->endvalue)) {
8878                     VALID_ERR2(XML_RELAXNG_ERR_LISTEXTRA,
8879                                ctxt->state->value);
8880                     ret = -1;
8881                 }
8882                 xmlFree(val);
8883                 ctxt->state->value = oldvalue;
8884                 ctxt->state->endvalue = oldend;
8885                 break;
8886             }
8887         case XML_RELAXNG_ONEORMORE:
8888             ret = xmlRelaxNGValidateValueList(ctxt, define->content);
8889             if (ret != 0) {
8890                 break;
8891             }
8892             /* no break on purpose */
8893         case XML_RELAXNG_ZEROORMORE:{
8894                 xmlChar *cur, *temp;
8895
8896                 if ((ctxt->state->value == NULL) ||
8897                     (*ctxt->state->value == 0)) {
8898                     ret = 0;
8899                     break;
8900                 }
8901                 oldflags = ctxt->flags;
8902                 ctxt->flags |= FLAGS_IGNORABLE;
8903                 cur = ctxt->state->value;
8904                 temp = NULL;
8905                 while ((cur != NULL) && (cur != ctxt->state->endvalue) &&
8906                        (temp != cur)) {
8907                     temp = cur;
8908                     ret =
8909                         xmlRelaxNGValidateValueList(ctxt, define->content);
8910                     if (ret != 0) {
8911                         ctxt->state->value = temp;
8912                         ret = 0;
8913                         break;
8914                     }
8915                     cur = ctxt->state->value;
8916                 }
8917                 ctxt->flags = oldflags;
8918                 if (ctxt->errNr > 0)
8919                     xmlRelaxNGPopErrors(ctxt, 0);
8920                 break;
8921             }
8922         case XML_RELAXNG_OPTIONAL:{
8923                 xmlChar *temp;
8924
8925                 if ((ctxt->state->value == NULL) ||
8926                     (*ctxt->state->value == 0)) {
8927                     ret = 0;
8928                     break;
8929                 }
8930                 oldflags = ctxt->flags;
8931                 ctxt->flags |= FLAGS_IGNORABLE;
8932                 temp = ctxt->state->value;
8933                 ret = xmlRelaxNGValidateValue(ctxt, define->content);
8934                 ctxt->flags = oldflags;
8935                 if (ret != 0) {
8936                     ctxt->state->value = temp;
8937                     if (ctxt->errNr > 0)
8938                         xmlRelaxNGPopErrors(ctxt, 0);
8939                     ret = 0;
8940                     break;
8941                 }
8942                 if (ctxt->errNr > 0)
8943                     xmlRelaxNGPopErrors(ctxt, 0);
8944                 break;
8945             }
8946         case XML_RELAXNG_EXCEPT:{
8947                 xmlRelaxNGDefinePtr list;
8948
8949                 list = define->content;
8950                 while (list != NULL) {
8951                     ret = xmlRelaxNGValidateValue(ctxt, list);
8952                     if (ret == 0) {
8953                         ret = -1;
8954                         break;
8955                     } else
8956                         ret = 0;
8957                     list = list->next;
8958                 }
8959                 break;
8960             }
8961         case XML_RELAXNG_DEF:
8962         case XML_RELAXNG_GROUP:{
8963                 xmlRelaxNGDefinePtr list;
8964
8965                 list = define->content;
8966                 while (list != NULL) {
8967                     ret = xmlRelaxNGValidateValue(ctxt, list);
8968                     if (ret != 0) {
8969                         ret = -1;
8970                         break;
8971                     } else
8972                         ret = 0;
8973                     list = list->next;
8974                 }
8975                 break;
8976             }
8977         case XML_RELAXNG_REF:
8978         case XML_RELAXNG_PARENTREF:
8979             if (define->content == NULL) {
8980                 VALID_ERR(XML_RELAXNG_ERR_NODEFINE);
8981                 ret = -1;
8982             } else {
8983                 ret = xmlRelaxNGValidateValue(ctxt, define->content);
8984             }
8985             break;
8986         default:
8987             TODO ret = -1;
8988     }
8989     return (ret);
8990 }
8991
8992 /**
8993  * xmlRelaxNGValidateValueContent:
8994  * @ctxt:  a Relax-NG validation context
8995  * @defines:  the list of definitions to verify
8996  *
8997  * Validate the given definitions for the current value
8998  *
8999  * Returns 0 if the validation succeeded or an error code.
9000  */
9001 static int
9002 xmlRelaxNGValidateValueContent(xmlRelaxNGValidCtxtPtr ctxt,
9003                                xmlRelaxNGDefinePtr defines)
9004 {
9005     int ret = 0;
9006
9007     while (defines != NULL) {
9008         ret = xmlRelaxNGValidateValue(ctxt, defines);
9009         if (ret != 0)
9010             break;
9011         defines = defines->next;
9012     }
9013     return (ret);
9014 }
9015
9016 /**
9017  * xmlRelaxNGAttributeMatch:
9018  * @ctxt:  a Relax-NG validation context
9019  * @define:  the definition to check
9020  * @prop:  the attribute
9021  *
9022  * Check if the attribute matches the definition nameClass
9023  *
9024  * Returns 1 if the attribute matches, 0 if no, or -1 in case of error
9025  */
9026 static int
9027 xmlRelaxNGAttributeMatch(xmlRelaxNGValidCtxtPtr ctxt,
9028                          xmlRelaxNGDefinePtr define, xmlAttrPtr prop)
9029 {
9030     int ret;
9031
9032     if (define->name != NULL) {
9033         if (!xmlStrEqual(define->name, prop->name))
9034             return (0);
9035     }
9036     if (define->ns != NULL) {
9037         if (define->ns[0] == 0) {
9038             if (prop->ns != NULL)
9039                 return (0);
9040         } else {
9041             if ((prop->ns == NULL) ||
9042                 (!xmlStrEqual(define->ns, prop->ns->href)))
9043                 return (0);
9044         }
9045     }
9046     if (define->nameClass == NULL)
9047         return (1);
9048     define = define->nameClass;
9049     if (define->type == XML_RELAXNG_EXCEPT) {
9050         xmlRelaxNGDefinePtr list;
9051
9052         list = define->content;
9053         while (list != NULL) {
9054             ret = xmlRelaxNGAttributeMatch(ctxt, list, prop);
9055             if (ret == 1)
9056                 return (0);
9057             if (ret < 0)
9058                 return (ret);
9059             list = list->next;
9060         }
9061     } else if (define->type == XML_RELAXNG_CHOICE) {
9062         xmlRelaxNGDefinePtr list;
9063
9064         list = define->nameClass;
9065         while (list != NULL) {
9066             ret = xmlRelaxNGAttributeMatch(ctxt, list, prop);
9067             if (ret == 1)
9068                 return (1);
9069             if (ret < 0)
9070                 return (ret);
9071             list = list->next;
9072         }
9073         return (0);
9074     } else {
9075     TODO}
9076     return (1);
9077 }
9078
9079 /**
9080  * xmlRelaxNGValidateAttribute:
9081  * @ctxt:  a Relax-NG validation context
9082  * @define:  the definition to verify
9083  *
9084  * Validate the given attribute definition for that node
9085  *
9086  * Returns 0 if the validation succeeded or an error code.
9087  */
9088 static int
9089 xmlRelaxNGValidateAttribute(xmlRelaxNGValidCtxtPtr ctxt,
9090                             xmlRelaxNGDefinePtr define)
9091 {
9092     int ret = 0, i;
9093     xmlChar *value, *oldvalue;
9094     xmlAttrPtr prop = NULL, tmp;
9095     xmlNodePtr oldseq;
9096
9097     if (ctxt->state->nbAttrLeft <= 0)
9098         return (-1);
9099     if (define->name != NULL) {
9100         for (i = 0; i < ctxt->state->nbAttrs; i++) {
9101             tmp = ctxt->state->attrs[i];
9102             if ((tmp != NULL) && (xmlStrEqual(define->name, tmp->name))) {
9103                 if ((((define->ns == NULL) || (define->ns[0] == 0)) &&
9104                      (tmp->ns == NULL)) ||
9105                     ((tmp->ns != NULL) &&
9106                      (xmlStrEqual(define->ns, tmp->ns->href)))) {
9107                     prop = tmp;
9108                     break;
9109                 }
9110             }
9111         }
9112         if (prop != NULL) {
9113             value = xmlNodeListGetString(prop->doc, prop->children, 1);
9114             oldvalue = ctxt->state->value;
9115             oldseq = ctxt->state->seq;
9116             ctxt->state->seq = (xmlNodePtr) prop;
9117             ctxt->state->value = value;
9118             ctxt->state->endvalue = NULL;
9119             ret = xmlRelaxNGValidateValueContent(ctxt, define->content);
9120             if (ctxt->state->value != NULL)
9121                 value = ctxt->state->value;
9122             if (value != NULL)
9123                 xmlFree(value);
9124             ctxt->state->value = oldvalue;
9125             ctxt->state->seq = oldseq;
9126             if (ret == 0) {
9127                 /*
9128                  * flag the attribute as processed
9129                  */
9130                 ctxt->state->attrs[i] = NULL;
9131                 ctxt->state->nbAttrLeft--;
9132             }
9133         } else {
9134             ret = -1;
9135         }
9136 #ifdef DEBUG
9137         xmlGenericError(xmlGenericErrorContext,
9138                         "xmlRelaxNGValidateAttribute(%s): %d\n",
9139                         define->name, ret);
9140 #endif
9141     } else {
9142         for (i = 0; i < ctxt->state->nbAttrs; i++) {
9143             tmp = ctxt->state->attrs[i];
9144             if ((tmp != NULL) &&
9145                 (xmlRelaxNGAttributeMatch(ctxt, define, tmp) == 1)) {
9146                 prop = tmp;
9147                 break;
9148             }
9149         }
9150         if (prop != NULL) {
9151             value = xmlNodeListGetString(prop->doc, prop->children, 1);
9152             oldvalue = ctxt->state->value;
9153             oldseq = ctxt->state->seq;
9154             ctxt->state->seq = (xmlNodePtr) prop;
9155             ctxt->state->value = value;
9156             ret = xmlRelaxNGValidateValueContent(ctxt, define->content);
9157             if (ctxt->state->value != NULL)
9158                 value = ctxt->state->value;
9159             if (value != NULL)
9160                 xmlFree(value);
9161             ctxt->state->value = oldvalue;
9162             ctxt->state->seq = oldseq;
9163             if (ret == 0) {
9164                 /*
9165                  * flag the attribute as processed
9166                  */
9167                 ctxt->state->attrs[i] = NULL;
9168                 ctxt->state->nbAttrLeft--;
9169             }
9170         } else {
9171             ret = -1;
9172         }
9173 #ifdef DEBUG
9174         if (define->ns != NULL) {
9175             xmlGenericError(xmlGenericErrorContext,
9176                             "xmlRelaxNGValidateAttribute(nsName ns = %s): %d\n",
9177                             define->ns, ret);
9178         } else {
9179             xmlGenericError(xmlGenericErrorContext,
9180                             "xmlRelaxNGValidateAttribute(anyName): %d\n",
9181                             ret);
9182         }
9183 #endif
9184     }
9185
9186     return (ret);
9187 }
9188
9189 /**
9190  * xmlRelaxNGValidateAttributeList:
9191  * @ctxt:  a Relax-NG validation context
9192  * @define:  the list of definition to verify
9193  *
9194  * Validate the given node against the list of attribute definitions
9195  *
9196  * Returns 0 if the validation succeeded or an error code.
9197  */
9198 static int
9199 xmlRelaxNGValidateAttributeList(xmlRelaxNGValidCtxtPtr ctxt,
9200                                 xmlRelaxNGDefinePtr defines)
9201 {
9202     int ret = 0, res;
9203     int needmore = 0;
9204     xmlRelaxNGDefinePtr cur;
9205
9206     cur = defines;
9207     while (cur != NULL) {
9208         if (cur->type == XML_RELAXNG_ATTRIBUTE) {
9209             if (xmlRelaxNGValidateAttribute(ctxt, cur) != 0)
9210                 ret = -1;
9211         } else
9212             needmore = 1;
9213         cur = cur->next;
9214     }
9215     if (!needmore)
9216         return (ret);
9217     cur = defines;
9218     while (cur != NULL) {
9219         if (cur->type != XML_RELAXNG_ATTRIBUTE) {
9220             if ((ctxt->state != NULL) || (ctxt->states != NULL)) {
9221                 res = xmlRelaxNGValidateDefinition(ctxt, cur);
9222                 if (res < 0)
9223                     ret = -1;
9224             } else {
9225                 VALID_ERR(XML_RELAXNG_ERR_NOSTATE);
9226                 return (-1);
9227             }
9228             if (res == -1)      /* continues on -2 */
9229                 break;
9230         }
9231         cur = cur->next;
9232     }
9233
9234     return (ret);
9235 }
9236
9237 /**
9238  * xmlRelaxNGNodeMatchesList:
9239  * @node:  the node
9240  * @list:  a NULL terminated array of definitions
9241  *
9242  * Check if a node can be matched by one of the definitions
9243  *
9244  * Returns 1 if matches 0 otherwise
9245  */
9246 static int
9247 xmlRelaxNGNodeMatchesList(xmlNodePtr node, xmlRelaxNGDefinePtr * list)
9248 {
9249     xmlRelaxNGDefinePtr cur;
9250     int i = 0, tmp;
9251
9252     if ((node == NULL) || (list == NULL))
9253         return (0);
9254
9255     cur = list[i++];
9256     while (cur != NULL) {
9257         if ((node->type == XML_ELEMENT_NODE) &&
9258             (cur->type == XML_RELAXNG_ELEMENT)) {
9259             tmp = xmlRelaxNGElementMatch(NULL, cur, node);
9260             if (tmp == 1)
9261                 return (1);
9262         } else if (((node->type == XML_TEXT_NODE) ||
9263                     (node->type == XML_CDATA_SECTION_NODE)) &&
9264                    (cur->type == XML_RELAXNG_TEXT)) {
9265             return (1);
9266         }
9267         cur = list[i++];
9268     }
9269     return (0);
9270 }
9271
9272 /**
9273  * xmlRelaxNGValidateInterleave:
9274  * @ctxt:  a Relax-NG validation context
9275  * @define:  the definition to verify
9276  *
9277  * Validate an interleave definition for a node.
9278  *
9279  * Returns 0 if the validation succeeded or an error code.
9280  */
9281 static int
9282 xmlRelaxNGValidateInterleave(xmlRelaxNGValidCtxtPtr ctxt,
9283                              xmlRelaxNGDefinePtr define)
9284 {
9285     int ret = 0, i, nbgroups;
9286     int errNr = ctxt->errNr;
9287     int oldflags;
9288
9289     xmlRelaxNGValidStatePtr oldstate;
9290     xmlRelaxNGPartitionPtr partitions;
9291     xmlRelaxNGInterleaveGroupPtr group = NULL;
9292     xmlNodePtr cur, start, last = NULL, lastchg = NULL, lastelem;
9293     xmlNodePtr *list = NULL, *lasts = NULL;
9294
9295     if (define->data != NULL) {
9296         partitions = (xmlRelaxNGPartitionPtr) define->data;
9297         nbgroups = partitions->nbgroups;
9298     } else {
9299         VALID_ERR(XML_RELAXNG_ERR_INTERNODATA);
9300         return (-1);
9301     }
9302     /*
9303      * Optimizations for MIXED
9304      */
9305     oldflags = ctxt->flags;
9306     if (define->dflags & IS_MIXED) {
9307         ctxt->flags |= FLAGS_MIXED_CONTENT;
9308         if (nbgroups == 2) {
9309             /*
9310              * this is a pure <mixed> case
9311              */
9312             if (ctxt->state != NULL)
9313                 ctxt->state->seq = xmlRelaxNGSkipIgnored(ctxt,
9314                                                          ctxt->state->seq);
9315             if (partitions->groups[0]->rule->type == XML_RELAXNG_TEXT)
9316                 ret = xmlRelaxNGValidateDefinition(ctxt,
9317                                                    partitions->groups[1]->
9318                                                    rule);
9319             else
9320                 ret = xmlRelaxNGValidateDefinition(ctxt,
9321                                                    partitions->groups[0]->
9322                                                    rule);
9323             if (ret == 0) {
9324                 if (ctxt->state != NULL)
9325                     ctxt->state->seq = xmlRelaxNGSkipIgnored(ctxt,
9326                                                              ctxt->state->
9327                                                              seq);
9328             }
9329             ctxt->flags = oldflags;
9330             return (ret);
9331         }
9332     }
9333
9334     /*
9335      * Build arrays to store the first and last node of the chain
9336      * pertaining to each group
9337      */
9338     list = (xmlNodePtr *) xmlMalloc(nbgroups * sizeof(xmlNodePtr));
9339     if (list == NULL) {
9340         xmlRngVErrMemory(ctxt, "validating\n");
9341         return (-1);
9342     }
9343     memset(list, 0, nbgroups * sizeof(xmlNodePtr));
9344     lasts = (xmlNodePtr *) xmlMalloc(nbgroups * sizeof(xmlNodePtr));
9345     if (lasts == NULL) {
9346         xmlRngVErrMemory(ctxt, "validating\n");
9347         return (-1);
9348     }
9349     memset(lasts, 0, nbgroups * sizeof(xmlNodePtr));
9350
9351     /*
9352      * Walk the sequence of children finding the right group and
9353      * sorting them in sequences.
9354      */
9355     cur = ctxt->state->seq;
9356     cur = xmlRelaxNGSkipIgnored(ctxt, cur);
9357     start = cur;
9358     while (cur != NULL) {
9359         ctxt->state->seq = cur;
9360         if ((partitions->triage != NULL) &&
9361             (partitions->flags & IS_DETERMINIST)) {
9362             void *tmp = NULL;
9363
9364             if ((cur->type == XML_TEXT_NODE) ||
9365                 (cur->type == XML_CDATA_SECTION_NODE)) {
9366                 tmp = xmlHashLookup2(partitions->triage, BAD_CAST "#text",
9367                                      NULL);
9368             } else if (cur->type == XML_ELEMENT_NODE) {
9369                 if (cur->ns != NULL) {
9370                     tmp = xmlHashLookup2(partitions->triage, cur->name,
9371                                          cur->ns->href);
9372                     if (tmp == NULL)
9373                         tmp = xmlHashLookup2(partitions->triage,
9374                                              BAD_CAST "#any",
9375                                              cur->ns->href);
9376                 } else
9377                     tmp =
9378                         xmlHashLookup2(partitions->triage, cur->name,
9379                                        NULL);
9380                 if (tmp == NULL)
9381                     tmp =
9382                         xmlHashLookup2(partitions->triage, BAD_CAST "#any",
9383                                        NULL);
9384             }
9385
9386             if (tmp == NULL) {
9387                 i = nbgroups;
9388             } else {
9389                 i = ((long) tmp) - 1;
9390                 if (partitions->flags & IS_NEEDCHECK) {
9391                     group = partitions->groups[i];
9392                     if (!xmlRelaxNGNodeMatchesList(cur, group->defs))
9393                         i = nbgroups;
9394                 }
9395             }
9396         } else {
9397             for (i = 0; i < nbgroups; i++) {
9398                 group = partitions->groups[i];
9399                 if (group == NULL)
9400                     continue;
9401                 if (xmlRelaxNGNodeMatchesList(cur, group->defs))
9402                     break;
9403             }
9404         }
9405         /*
9406          * We break as soon as an element not matched is found
9407          */
9408         if (i >= nbgroups) {
9409             break;
9410         }
9411         if (lasts[i] != NULL) {
9412             lasts[i]->next = cur;
9413             lasts[i] = cur;
9414         } else {
9415             list[i] = cur;
9416             lasts[i] = cur;
9417         }
9418         if (cur->next != NULL)
9419             lastchg = cur->next;
9420         else
9421             lastchg = cur;
9422         cur = xmlRelaxNGSkipIgnored(ctxt, cur->next);
9423     }
9424     if (ret != 0) {
9425         VALID_ERR(XML_RELAXNG_ERR_INTERSEQ);
9426         ret = -1;
9427         goto done;
9428     }
9429     lastelem = cur;
9430     oldstate = ctxt->state;
9431     for (i = 0; i < nbgroups; i++) {
9432         ctxt->state = xmlRelaxNGCopyValidState(ctxt, oldstate);
9433         if (ctxt->state == NULL) {
9434             ret = -1;
9435             break;
9436         }
9437         group = partitions->groups[i];
9438         if (lasts[i] != NULL) {
9439             last = lasts[i]->next;
9440             lasts[i]->next = NULL;
9441         }
9442         ctxt->state->seq = list[i];
9443         ret = xmlRelaxNGValidateDefinition(ctxt, group->rule);
9444         if (ret != 0)
9445             break;
9446         if (ctxt->state != NULL) {
9447             cur = ctxt->state->seq;
9448             cur = xmlRelaxNGSkipIgnored(ctxt, cur);
9449             xmlRelaxNGFreeValidState(ctxt, oldstate);
9450             oldstate = ctxt->state;
9451             ctxt->state = NULL;
9452             if (cur != NULL) {
9453                 VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA, cur->name);
9454                 ret = -1;
9455                 ctxt->state = oldstate;
9456                 goto done;
9457             }
9458         } else if (ctxt->states != NULL) {
9459             int j;
9460             int found = 0;
9461             int best = -1;
9462             int lowattr = -1;
9463
9464             /*
9465              * PBM: what happen if there is attributes checks in the interleaves
9466              */
9467
9468             for (j = 0; j < ctxt->states->nbState; j++) {
9469                 cur = ctxt->states->tabState[j]->seq;
9470                 cur = xmlRelaxNGSkipIgnored(ctxt, cur);
9471                 if (cur == NULL) {
9472                     if (found == 0) {
9473                         lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9474                         best = j;
9475                     }
9476                     found = 1;
9477                     if (ctxt->states->tabState[j]->nbAttrLeft <= lowattr) {
9478                         /* try  to keep the latest one to mach old heuristic */
9479                         lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9480                         best = j;
9481                     }
9482                     if (lowattr == 0)
9483                         break;
9484                 } else if (found == 0) {
9485                     if (lowattr == -1) {
9486                         lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9487                         best = j;
9488                     } else
9489                     if (ctxt->states->tabState[j]->nbAttrLeft <= lowattr)  {
9490                         /* try  to keep the latest one to mach old heuristic */
9491                         lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9492                         best = j;
9493                     }
9494                 }
9495             }
9496             /*
9497              * BIG PBM: here we pick only one restarting point :-(
9498              */
9499             if (ctxt->states->nbState > 0) {
9500                 xmlRelaxNGFreeValidState(ctxt, oldstate);
9501                 if (best != -1) {
9502                     oldstate = ctxt->states->tabState[best];
9503                     ctxt->states->tabState[best] = NULL;
9504                 } else {
9505                     oldstate =
9506                         ctxt->states->tabState[ctxt->states->nbState - 1];
9507                     ctxt->states->tabState[ctxt->states->nbState - 1] = NULL;
9508                     ctxt->states->nbState--;
9509                 }
9510             }
9511             for (j = 0; j < ctxt->states->nbState ; j++) {
9512                 xmlRelaxNGFreeValidState(ctxt, ctxt->states->tabState[j]);
9513             }
9514             xmlRelaxNGFreeStates(ctxt, ctxt->states);
9515             ctxt->states = NULL;
9516             if (found == 0) {
9517                 if (cur == NULL) {
9518                     VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA,
9519                                (const xmlChar *) "noname");
9520                 } else {
9521                     VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA, cur->name);
9522                 }
9523                 ret = -1;
9524                 ctxt->state = oldstate;
9525                 goto done;
9526             }
9527         } else {
9528             ret = -1;
9529             break;
9530         }
9531         if (lasts[i] != NULL) {
9532             lasts[i]->next = last;
9533         }
9534     }
9535     if (ctxt->state != NULL)
9536         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
9537     ctxt->state = oldstate;
9538     ctxt->state->seq = lastelem;
9539     if (ret != 0) {
9540         VALID_ERR(XML_RELAXNG_ERR_INTERSEQ);
9541         ret = -1;
9542         goto done;
9543     }
9544
9545   done:
9546     ctxt->flags = oldflags;
9547     /*
9548      * builds the next links chain from the prev one
9549      */
9550     cur = lastchg;
9551     while (cur != NULL) {
9552         if ((cur == start) || (cur->prev == NULL))
9553             break;
9554         cur->prev->next = cur;
9555         cur = cur->prev;
9556     }
9557     if (ret == 0) {
9558         if (ctxt->errNr > errNr)
9559             xmlRelaxNGPopErrors(ctxt, errNr);
9560     }
9561
9562     xmlFree(list);
9563     xmlFree(lasts);
9564     return (ret);
9565 }
9566
9567 /**
9568  * xmlRelaxNGValidateDefinitionList:
9569  * @ctxt:  a Relax-NG validation context
9570  * @define:  the list of definition to verify
9571  *
9572  * Validate the given node content against the (list) of definitions
9573  *
9574  * Returns 0 if the validation succeeded or an error code.
9575  */
9576 static int
9577 xmlRelaxNGValidateDefinitionList(xmlRelaxNGValidCtxtPtr ctxt,
9578                                  xmlRelaxNGDefinePtr defines)
9579 {
9580     int ret = 0, res;
9581
9582
9583     if (defines == NULL) {
9584         VALID_ERR2(XML_RELAXNG_ERR_INTERNAL,
9585                    BAD_CAST "NULL definition list");
9586         return (-1);
9587     }
9588     while (defines != NULL) {
9589         if ((ctxt->state != NULL) || (ctxt->states != NULL)) {
9590             res = xmlRelaxNGValidateDefinition(ctxt, defines);
9591             if (res < 0)
9592                 ret = -1;
9593         } else {
9594             VALID_ERR(XML_RELAXNG_ERR_NOSTATE);
9595             return (-1);
9596         }
9597         if (res == -1)          /* continues on -2 */
9598             break;
9599         defines = defines->next;
9600     }
9601
9602     return (ret);
9603 }
9604
9605 /**
9606  * xmlRelaxNGElementMatch:
9607  * @ctxt:  a Relax-NG validation context
9608  * @define:  the definition to check
9609  * @elem:  the element
9610  *
9611  * Check if the element matches the definition nameClass
9612  *
9613  * Returns 1 if the element matches, 0 if no, or -1 in case of error
9614  */
9615 static int
9616 xmlRelaxNGElementMatch(xmlRelaxNGValidCtxtPtr ctxt,
9617                        xmlRelaxNGDefinePtr define, xmlNodePtr elem)
9618 {
9619     int ret = 0, oldflags = 0;
9620
9621     if (define->name != NULL) {
9622         if (!xmlStrEqual(elem->name, define->name)) {
9623             VALID_ERR3(XML_RELAXNG_ERR_ELEMNAME, define->name, elem->name);
9624             return (0);
9625         }
9626     }
9627     if ((define->ns != NULL) && (define->ns[0] != 0)) {
9628         if (elem->ns == NULL) {
9629             VALID_ERR2(XML_RELAXNG_ERR_ELEMNONS, elem->name);
9630             return (0);
9631         } else if (!xmlStrEqual(elem->ns->href, define->ns)) {
9632             VALID_ERR3(XML_RELAXNG_ERR_ELEMWRONGNS,
9633                        elem->name, define->ns);
9634             return (0);
9635         }
9636     } else if ((elem->ns != NULL) && (define->ns != NULL) &&
9637                (define->name == NULL)) {
9638         VALID_ERR2(XML_RELAXNG_ERR_ELEMEXTRANS, elem->name);
9639         return (0);
9640     } else if ((elem->ns != NULL) && (define->name != NULL)) {
9641         VALID_ERR2(XML_RELAXNG_ERR_ELEMEXTRANS, define->name);
9642         return (0);
9643     }
9644
9645     if (define->nameClass == NULL)
9646         return (1);
9647
9648     define = define->nameClass;
9649     if (define->type == XML_RELAXNG_EXCEPT) {
9650         xmlRelaxNGDefinePtr list;
9651
9652         if (ctxt != NULL) {
9653             oldflags = ctxt->flags;
9654             ctxt->flags |= FLAGS_IGNORABLE;
9655         }
9656
9657         list = define->content;
9658         while (list != NULL) {
9659             ret = xmlRelaxNGElementMatch(ctxt, list, elem);
9660             if (ret == 1) {
9661                 if (ctxt != NULL)
9662                     ctxt->flags = oldflags;
9663                 return (0);
9664             }
9665             if (ret < 0) {
9666                 if (ctxt != NULL)
9667                     ctxt->flags = oldflags;
9668                 return (ret);
9669             }
9670             list = list->next;
9671         }
9672         ret = 1;
9673         if (ctxt != NULL) {
9674             ctxt->flags = oldflags;
9675         }
9676     } else if (define->type == XML_RELAXNG_CHOICE) {
9677         xmlRelaxNGDefinePtr list;
9678
9679         if (ctxt != NULL) {
9680             oldflags = ctxt->flags;
9681             ctxt->flags |= FLAGS_IGNORABLE;
9682         }
9683
9684         list = define->nameClass;
9685         while (list != NULL) {
9686             ret = xmlRelaxNGElementMatch(ctxt, list, elem);
9687             if (ret == 1) {
9688                 if (ctxt != NULL)
9689                     ctxt->flags = oldflags;
9690                 return (1);
9691             }
9692             if (ret < 0) {
9693                 if (ctxt != NULL)
9694                     ctxt->flags = oldflags;
9695                 return (ret);
9696             }
9697             list = list->next;
9698         }
9699         if (ctxt != NULL) {
9700             if (ret != 0) {
9701                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9702                     xmlRelaxNGDumpValidError(ctxt);
9703             } else {
9704                 if (ctxt->errNr > 0)
9705                     xmlRelaxNGPopErrors(ctxt, 0);
9706             }
9707         }
9708         ret = 0;
9709         if (ctxt != NULL) {
9710             ctxt->flags = oldflags;
9711         }
9712     } else {
9713         TODO ret = -1;
9714     }
9715     return (ret);
9716 }
9717
9718 /**
9719  * xmlRelaxNGBestState:
9720  * @ctxt:  a Relax-NG validation context
9721  *
9722  * Find the "best" state in the ctxt->states list of states to report
9723  * errors about. I.e. a state with no element left in the child list
9724  * or the one with the less attributes left.
9725  * This is called only if a falidation error was detected
9726  *
9727  * Returns the index of the "best" state or -1 in case of error
9728  */
9729 static int
9730 xmlRelaxNGBestState(xmlRelaxNGValidCtxtPtr ctxt)
9731 {
9732     xmlRelaxNGValidStatePtr state;
9733     int i, tmp;
9734     int best = -1;
9735     int value = 1000000;
9736
9737     if ((ctxt == NULL) || (ctxt->states == NULL) ||
9738         (ctxt->states->nbState <= 0))
9739         return (-1);
9740
9741     for (i = 0; i < ctxt->states->nbState; i++) {
9742         state = ctxt->states->tabState[i];
9743         if (state == NULL)
9744             continue;
9745         if (state->seq != NULL) {
9746             if ((best == -1) || (value > 100000)) {
9747                 value = 100000;
9748                 best = i;
9749             }
9750         } else {
9751             tmp = state->nbAttrLeft;
9752             if ((best == -1) || (value > tmp)) {
9753                 value = tmp;
9754                 best = i;
9755             }
9756         }
9757     }
9758     return (best);
9759 }
9760
9761 /**
9762  * xmlRelaxNGLogBestError:
9763  * @ctxt:  a Relax-NG validation context
9764  *
9765  * Find the "best" state in the ctxt->states list of states to report
9766  * errors about and log it.
9767  */
9768 static void
9769 xmlRelaxNGLogBestError(xmlRelaxNGValidCtxtPtr ctxt)
9770 {
9771     int best;
9772
9773     if ((ctxt == NULL) || (ctxt->states == NULL) ||
9774         (ctxt->states->nbState <= 0))
9775         return;
9776
9777     best = xmlRelaxNGBestState(ctxt);
9778     if ((best >= 0) && (best < ctxt->states->nbState)) {
9779         ctxt->state = ctxt->states->tabState[best];
9780
9781         xmlRelaxNGValidateElementEnd(ctxt, 1);
9782     }
9783 }
9784
9785 /**
9786  * xmlRelaxNGValidateElementEnd:
9787  * @ctxt:  a Relax-NG validation context
9788  * @dolog:  indicate that error logging should be done
9789  *
9790  * Validate the end of the element, implements check that
9791  * there is nothing left not consumed in the element content
9792  * or in the attribute list.
9793  *
9794  * Returns 0 if the validation succeeded or an error code.
9795  */
9796 static int
9797 xmlRelaxNGValidateElementEnd(xmlRelaxNGValidCtxtPtr ctxt, int dolog)
9798 {
9799     int i;
9800     xmlRelaxNGValidStatePtr state;
9801
9802     state = ctxt->state;
9803     if (state->seq != NULL) {
9804         state->seq = xmlRelaxNGSkipIgnored(ctxt, state->seq);
9805         if (state->seq != NULL) {
9806             if (dolog) {
9807                 VALID_ERR3(XML_RELAXNG_ERR_EXTRACONTENT,
9808                            state->node->name, state->seq->name);
9809             }
9810             return (-1);
9811         }
9812     }
9813     for (i = 0; i < state->nbAttrs; i++) {
9814         if (state->attrs[i] != NULL) {
9815             if (dolog) {
9816                 VALID_ERR3(XML_RELAXNG_ERR_INVALIDATTR,
9817                            state->attrs[i]->name, state->node->name);
9818             }
9819             return (-1 - i);
9820         }
9821     }
9822     return (0);
9823 }
9824
9825 /**
9826  * xmlRelaxNGValidateState:
9827  * @ctxt:  a Relax-NG validation context
9828  * @define:  the definition to verify
9829  *
9830  * Validate the current state against the definition
9831  *
9832  * Returns 0 if the validation succeeded or an error code.
9833  */
9834 static int
9835 xmlRelaxNGValidateState(xmlRelaxNGValidCtxtPtr ctxt,
9836                         xmlRelaxNGDefinePtr define)
9837 {
9838     xmlNodePtr node;
9839     int ret = 0, i, tmp, oldflags, errNr;
9840     xmlRelaxNGValidStatePtr oldstate = NULL, state;
9841
9842     if (define == NULL) {
9843         VALID_ERR(XML_RELAXNG_ERR_NODEFINE);
9844         return (-1);
9845     }
9846
9847     if (ctxt->state != NULL) {
9848         node = ctxt->state->seq;
9849     } else {
9850         node = NULL;
9851     }
9852 #ifdef DEBUG
9853     for (i = 0; i < ctxt->depth; i++)
9854         xmlGenericError(xmlGenericErrorContext, " ");
9855     xmlGenericError(xmlGenericErrorContext,
9856                     "Start validating %s ", xmlRelaxNGDefName(define));
9857     if (define->name != NULL)
9858         xmlGenericError(xmlGenericErrorContext, "%s ", define->name);
9859     if ((node != NULL) && (node->name != NULL))
9860         xmlGenericError(xmlGenericErrorContext, "on %s\n", node->name);
9861     else
9862         xmlGenericError(xmlGenericErrorContext, "\n");
9863 #endif
9864     ctxt->depth++;
9865     switch (define->type) {
9866         case XML_RELAXNG_EMPTY:
9867             xmlRelaxNGSkipIgnored(ctxt, node);
9868             ret = 0;
9869             break;
9870         case XML_RELAXNG_NOT_ALLOWED:
9871             ret = -1;
9872             break;
9873         case XML_RELAXNG_TEXT:
9874             while ((node != NULL) &&
9875                    ((node->type == XML_TEXT_NODE) ||
9876                     (node->type == XML_COMMENT_NODE) ||
9877                     (node->type == XML_PI_NODE) ||
9878                     (node->type == XML_CDATA_SECTION_NODE)))
9879                 node = node->next;
9880             ctxt->state->seq = node;
9881             break;
9882         case XML_RELAXNG_ELEMENT:
9883             errNr = ctxt->errNr;
9884             node = xmlRelaxNGSkipIgnored(ctxt, node);
9885             if (node == NULL) {
9886                 VALID_ERR2(XML_RELAXNG_ERR_NOELEM, define->name);
9887                 ret = -1;
9888                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9889                     xmlRelaxNGDumpValidError(ctxt);
9890                 break;
9891             }
9892             if (node->type != XML_ELEMENT_NODE) {
9893                 VALID_ERR(XML_RELAXNG_ERR_NOTELEM);
9894                 ret = -1;
9895                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9896                     xmlRelaxNGDumpValidError(ctxt);
9897                 break;
9898             }
9899             /*
9900              * This node was already validated successfully against
9901              * this definition.
9902              */
9903             if (node->psvi == define) {
9904                 ctxt->state->seq = xmlRelaxNGSkipIgnored(ctxt, node->next);
9905                 if (ctxt->errNr > errNr)
9906                     xmlRelaxNGPopErrors(ctxt, errNr);
9907                 if (ctxt->errNr != 0) {
9908                     while ((ctxt->err != NULL) &&
9909                            (((ctxt->err->err == XML_RELAXNG_ERR_ELEMNAME)
9910                              && (xmlStrEqual(ctxt->err->arg2, node->name)))
9911                             ||
9912                             ((ctxt->err->err ==
9913                               XML_RELAXNG_ERR_ELEMEXTRANS)
9914                              && (xmlStrEqual(ctxt->err->arg1, node->name)))
9915                             || (ctxt->err->err == XML_RELAXNG_ERR_NOELEM)
9916                             || (ctxt->err->err ==
9917                                 XML_RELAXNG_ERR_NOTELEM)))
9918                         xmlRelaxNGValidErrorPop(ctxt);
9919                 }
9920                 break;
9921             }
9922
9923             ret = xmlRelaxNGElementMatch(ctxt, define, node);
9924             if (ret <= 0) {
9925                 ret = -1;
9926                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9927                     xmlRelaxNGDumpValidError(ctxt);
9928                 break;
9929             }
9930             ret = 0;
9931             if (ctxt->errNr != 0) {
9932                 if (ctxt->errNr > errNr)
9933                     xmlRelaxNGPopErrors(ctxt, errNr);
9934                 while ((ctxt->err != NULL) &&
9935                        (((ctxt->err->err == XML_RELAXNG_ERR_ELEMNAME) &&
9936                          (xmlStrEqual(ctxt->err->arg2, node->name))) ||
9937                         ((ctxt->err->err == XML_RELAXNG_ERR_ELEMEXTRANS) &&
9938                          (xmlStrEqual(ctxt->err->arg1, node->name))) ||
9939                         (ctxt->err->err == XML_RELAXNG_ERR_NOELEM) ||
9940                         (ctxt->err->err == XML_RELAXNG_ERR_NOTELEM)))
9941                     xmlRelaxNGValidErrorPop(ctxt);
9942             }
9943             errNr = ctxt->errNr;
9944
9945             oldflags = ctxt->flags;
9946             if (ctxt->flags & FLAGS_MIXED_CONTENT) {
9947                 ctxt->flags -= FLAGS_MIXED_CONTENT;
9948             }
9949             state = xmlRelaxNGNewValidState(ctxt, node);
9950             if (state == NULL) {
9951                 ret = -1;
9952                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9953                     xmlRelaxNGDumpValidError(ctxt);
9954                 break;
9955             }
9956
9957             oldstate = ctxt->state;
9958             ctxt->state = state;
9959             if (define->attrs != NULL) {
9960                 tmp = xmlRelaxNGValidateAttributeList(ctxt, define->attrs);
9961                 if (tmp != 0) {
9962                     ret = -1;
9963                     VALID_ERR2(XML_RELAXNG_ERR_ATTRVALID, node->name);
9964                 }
9965             }
9966             if (define->contModel != NULL) {
9967                 xmlRelaxNGValidStatePtr nstate, tmpstate = ctxt->state;
9968                 xmlRelaxNGStatesPtr tmpstates = ctxt->states;
9969                 xmlNodePtr nseq;
9970
9971                 nstate = xmlRelaxNGNewValidState(ctxt, node);
9972                 ctxt->state = nstate;
9973                 ctxt->states = NULL;
9974
9975                 tmp = xmlRelaxNGValidateCompiledContent(ctxt,
9976                                                         define->contModel,
9977                                                         ctxt->state->seq);
9978                 nseq = ctxt->state->seq;
9979                 ctxt->state = tmpstate;
9980                 ctxt->states = tmpstates;
9981                 xmlRelaxNGFreeValidState(ctxt, nstate);
9982
9983 #ifdef DEBUG_COMPILE
9984                 xmlGenericError(xmlGenericErrorContext,
9985                                 "Validating content of '%s' : %d\n",
9986                                 define->name, tmp);
9987 #endif
9988                 if (tmp != 0)
9989                     ret = -1;
9990
9991                 if (ctxt->states != NULL) {
9992                     tmp = -1;
9993
9994                     for (i = 0; i < ctxt->states->nbState; i++) {
9995                         state = ctxt->states->tabState[i];
9996                         ctxt->state = state;
9997                         ctxt->state->seq = nseq;
9998
9999                         if (xmlRelaxNGValidateElementEnd(ctxt, 0) == 0) {
10000                             tmp = 0;
10001                             break;
10002                         }
10003                     }
10004                     if (tmp != 0) {
10005                         /*
10006                          * validation error, log the message for the "best" one
10007                          */
10008                         ctxt->flags |= FLAGS_IGNORABLE;
10009                         xmlRelaxNGLogBestError(ctxt);
10010                     }
10011                     for (i = 0; i < ctxt->states->nbState; i++) {
10012                         xmlRelaxNGFreeValidState(ctxt,
10013                                                  ctxt->states->
10014                                                  tabState[i]);
10015                     }
10016                     xmlRelaxNGFreeStates(ctxt, ctxt->states);
10017                     ctxt->flags = oldflags;
10018                     ctxt->states = NULL;
10019                     if ((ret == 0) && (tmp == -1))
10020                         ret = -1;
10021                 } else {
10022                     state = ctxt->state;
10023                     if (ctxt->state != NULL)
10024                         ctxt->state->seq = nseq;
10025                     if (ret == 0)
10026                         ret = xmlRelaxNGValidateElementEnd(ctxt, 1);
10027                     xmlRelaxNGFreeValidState(ctxt, state);
10028                 }
10029             } else {
10030                 if (define->content != NULL) {
10031                     tmp = xmlRelaxNGValidateDefinitionList(ctxt,
10032                                                            define->
10033                                                            content);
10034                     if (tmp != 0) {
10035                         ret = -1;
10036                         if (ctxt->state == NULL) {
10037                             ctxt->state = oldstate;
10038                             VALID_ERR2(XML_RELAXNG_ERR_CONTENTVALID,
10039                                        node->name);
10040                             ctxt->state = NULL;
10041                         } else {
10042                             VALID_ERR2(XML_RELAXNG_ERR_CONTENTVALID,
10043                                        node->name);
10044                         }
10045
10046                     }
10047                 }
10048                 if (ctxt->states != NULL) {
10049                     tmp = -1;
10050
10051                     for (i = 0; i < ctxt->states->nbState; i++) {
10052                         state = ctxt->states->tabState[i];
10053                         ctxt->state = state;
10054
10055                         if (xmlRelaxNGValidateElementEnd(ctxt, 0) == 0) {
10056                             tmp = 0;
10057                             break;
10058                         }
10059                     }
10060                     if (tmp != 0) {
10061                         /*
10062                          * validation error, log the message for the "best" one
10063                          */
10064                         ctxt->flags |= FLAGS_IGNORABLE;
10065                         xmlRelaxNGLogBestError(ctxt);
10066                     }
10067                     for (i = 0; i < ctxt->states->nbState; i++) {
10068                         xmlRelaxNGFreeValidState(ctxt,
10069                                                  ctxt->states->tabState[i]);
10070                         ctxt->states->tabState[i] = NULL;
10071                     }
10072                     xmlRelaxNGFreeStates(ctxt, ctxt->states);
10073                     ctxt->flags = oldflags;
10074                     ctxt->states = NULL;
10075                     if ((ret == 0) && (tmp == -1))
10076                         ret = -1;
10077                 } else {
10078                     state = ctxt->state;
10079                     if (ret == 0)
10080                         ret = xmlRelaxNGValidateElementEnd(ctxt, 1);
10081                     xmlRelaxNGFreeValidState(ctxt, state);
10082                 }
10083             }
10084             if (ret == 0) {
10085                 node->psvi = define;
10086             }
10087             ctxt->flags = oldflags;
10088             ctxt->state = oldstate;
10089             if (oldstate != NULL)
10090                 oldstate->seq = xmlRelaxNGSkipIgnored(ctxt, node->next);
10091             if (ret != 0) {
10092                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0) {
10093                     xmlRelaxNGDumpValidError(ctxt);
10094                     ret = 0;
10095 #if 0
10096                 } else {
10097                     ret = -2;
10098 #endif
10099                 }
10100             } else {
10101                 if (ctxt->errNr > errNr)
10102                     xmlRelaxNGPopErrors(ctxt, errNr);
10103             }
10104
10105 #ifdef DEBUG
10106             xmlGenericError(xmlGenericErrorContext,
10107                             "xmlRelaxNGValidateDefinition(): validated %s : %d",
10108                             node->name, ret);
10109             if (oldstate == NULL)
10110                 xmlGenericError(xmlGenericErrorContext, ": no state\n");
10111             else if (oldstate->seq == NULL)
10112                 xmlGenericError(xmlGenericErrorContext, ": done\n");
10113             else if (oldstate->seq->type == XML_ELEMENT_NODE)
10114                 xmlGenericError(xmlGenericErrorContext, ": next elem %s\n",
10115                                 oldstate->seq->name);
10116             else
10117                 xmlGenericError(xmlGenericErrorContext, ": next %s %d\n",
10118                                 oldstate->seq->name, oldstate->seq->type);
10119 #endif
10120             break;
10121         case XML_RELAXNG_OPTIONAL:{
10122                 errNr = ctxt->errNr;
10123                 oldflags = ctxt->flags;
10124                 ctxt->flags |= FLAGS_IGNORABLE;
10125                 oldstate = xmlRelaxNGCopyValidState(ctxt, ctxt->state);
10126                 ret =
10127                     xmlRelaxNGValidateDefinitionList(ctxt,
10128                                                      define->content);
10129                 if (ret != 0) {
10130                     if (ctxt->state != NULL)
10131                         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10132                     ctxt->state = oldstate;
10133                     ctxt->flags = oldflags;
10134                     ret = 0;
10135                     if (ctxt->errNr > errNr)
10136                         xmlRelaxNGPopErrors(ctxt, errNr);
10137                     break;
10138                 }
10139                 if (ctxt->states != NULL) {
10140                     xmlRelaxNGAddStates(ctxt, ctxt->states, oldstate);
10141                 } else {
10142                     ctxt->states = xmlRelaxNGNewStates(ctxt, 1);
10143                     if (ctxt->states == NULL) {
10144                         xmlRelaxNGFreeValidState(ctxt, oldstate);
10145                         ctxt->flags = oldflags;
10146                         ret = -1;
10147                         if (ctxt->errNr > errNr)
10148                             xmlRelaxNGPopErrors(ctxt, errNr);
10149                         break;
10150                     }
10151                     xmlRelaxNGAddStates(ctxt, ctxt->states, oldstate);
10152                     xmlRelaxNGAddStates(ctxt, ctxt->states, ctxt->state);
10153                     ctxt->state = NULL;
10154                 }
10155                 ctxt->flags = oldflags;
10156                 ret = 0;
10157                 if (ctxt->errNr > errNr)
10158                     xmlRelaxNGPopErrors(ctxt, errNr);
10159                 break;
10160             }
10161         case XML_RELAXNG_ONEORMORE:
10162             errNr = ctxt->errNr;
10163             ret = xmlRelaxNGValidateDefinitionList(ctxt, define->content);
10164             if (ret != 0) {
10165                 break;
10166             }
10167             if (ctxt->errNr > errNr)
10168                 xmlRelaxNGPopErrors(ctxt, errNr);
10169             /* no break on purpose */
10170         case XML_RELAXNG_ZEROORMORE:{
10171                 int progress;
10172                 xmlRelaxNGStatesPtr states = NULL, res = NULL;
10173                 int base, j;
10174
10175                 errNr = ctxt->errNr;
10176                 res = xmlRelaxNGNewStates(ctxt, 1);
10177                 if (res == NULL) {
10178                     ret = -1;
10179                     break;
10180                 }
10181                 /*
10182                  * All the input states are also exit states
10183                  */
10184                 if (ctxt->state != NULL) {
10185                     xmlRelaxNGAddStates(ctxt, res,
10186                                         xmlRelaxNGCopyValidState(ctxt,
10187                                                                  ctxt->
10188                                                                  state));
10189                 } else {
10190                     for (j = 0; j < ctxt->states->nbState; j++) {
10191                         xmlRelaxNGAddStates(ctxt, res,
10192                             xmlRelaxNGCopyValidState(ctxt,
10193                                             ctxt->states->tabState[j]));
10194                     }
10195                 }
10196                 oldflags = ctxt->flags;
10197                 ctxt->flags |= FLAGS_IGNORABLE;
10198                 do {
10199                     progress = 0;
10200                     base = res->nbState;
10201
10202                     if (ctxt->states != NULL) {
10203                         states = ctxt->states;
10204                         for (i = 0; i < states->nbState; i++) {
10205                             ctxt->state = states->tabState[i];
10206                             ctxt->states = NULL;
10207                             ret = xmlRelaxNGValidateDefinitionList(ctxt,
10208                                                                    define->
10209                                                                    content);
10210                             if (ret == 0) {
10211                                 if (ctxt->state != NULL) {
10212                                     tmp = xmlRelaxNGAddStates(ctxt, res,
10213                                                               ctxt->state);
10214                                     ctxt->state = NULL;
10215                                     if (tmp == 1)
10216                                         progress = 1;
10217                                 } else if (ctxt->states != NULL) {
10218                                     for (j = 0; j < ctxt->states->nbState;
10219                                          j++) {
10220                                         tmp =
10221                                             xmlRelaxNGAddStates(ctxt, res,
10222                                                    ctxt->states->tabState[j]);
10223                                         if (tmp == 1)
10224                                             progress = 1;
10225                                     }
10226                                     xmlRelaxNGFreeStates(ctxt,
10227                                                          ctxt->states);
10228                                     ctxt->states = NULL;
10229                                 }
10230                             } else {
10231                                 if (ctxt->state != NULL) {
10232                                     xmlRelaxNGFreeValidState(ctxt,
10233                                                              ctxt->state);
10234                                     ctxt->state = NULL;
10235                                 }
10236                             }
10237                         }
10238                     } else {
10239                         ret = xmlRelaxNGValidateDefinitionList(ctxt,
10240                                                                define->
10241                                                                content);
10242                         if (ret != 0) {
10243                             xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10244                             ctxt->state = NULL;
10245                         } else {
10246                             base = res->nbState;
10247                             if (ctxt->state != NULL) {
10248                                 tmp = xmlRelaxNGAddStates(ctxt, res,
10249                                                           ctxt->state);
10250                                 ctxt->state = NULL;
10251                                 if (tmp == 1)
10252                                     progress = 1;
10253                             } else if (ctxt->states != NULL) {
10254                                 for (j = 0; j < ctxt->states->nbState; j++) {
10255                                     tmp = xmlRelaxNGAddStates(ctxt, res,
10256                                                ctxt->states->tabState[j]);
10257                                     if (tmp == 1)
10258                                         progress = 1;
10259                                 }
10260                                 if (states == NULL) {
10261                                     states = ctxt->states;
10262                                 } else {
10263                                     xmlRelaxNGFreeStates(ctxt,
10264                                                          ctxt->states);
10265                                 }
10266                                 ctxt->states = NULL;
10267                             }
10268                         }
10269                     }
10270                     if (progress) {
10271                         /*
10272                          * Collect all the new nodes added at that step
10273                          * and make them the new node set
10274                          */
10275                         if (res->nbState - base == 1) {
10276                             ctxt->state = xmlRelaxNGCopyValidState(ctxt,
10277                                                                    res->
10278                                                                    tabState
10279                                                                    [base]);
10280                         } else {
10281                             if (states == NULL) {
10282                                 xmlRelaxNGNewStates(ctxt,
10283                                                     res->nbState - base);
10284                                 states = ctxt->states;
10285                                 if (states == NULL) {
10286                                     progress = 0;
10287                                     break;
10288                                 }
10289                             }
10290                             states->nbState = 0;
10291                             for (i = base; i < res->nbState; i++)
10292                                 xmlRelaxNGAddStates(ctxt, states,
10293                                                     xmlRelaxNGCopyValidState
10294                                                     (ctxt, res->tabState[i]));
10295                             ctxt->states = states;
10296                         }
10297                     }
10298                 } while (progress == 1);
10299                 if (states != NULL) {
10300                     xmlRelaxNGFreeStates(ctxt, states);
10301                 }
10302                 ctxt->states = res;
10303                 ctxt->flags = oldflags;
10304 #if 0
10305                 /*
10306                  * errors may have to be propagated back...
10307                  */
10308                 if (ctxt->errNr > errNr)
10309                     xmlRelaxNGPopErrors(ctxt, errNr);
10310 #endif
10311                 ret = 0;
10312                 break;
10313             }
10314         case XML_RELAXNG_CHOICE:{
10315                 xmlRelaxNGDefinePtr list = NULL;
10316                 xmlRelaxNGStatesPtr states = NULL;
10317
10318                 node = xmlRelaxNGSkipIgnored(ctxt, node);
10319
10320                 errNr = ctxt->errNr;
10321                 if ((define->dflags & IS_TRIABLE) && (define->data != NULL) &&
10322                     (node != NULL)) {
10323                     /*
10324                      * node == NULL can't be optimized since IS_TRIABLE
10325                      * doesn't account for choice which may lead to
10326                      * only attributes.
10327                      */
10328                     xmlHashTablePtr triage =
10329                         (xmlHashTablePtr) define->data;
10330
10331                     /*
10332                      * Something we can optimize cleanly there is only one
10333                      * possble branch out !
10334                      */
10335                     if ((node->type == XML_TEXT_NODE) ||
10336                         (node->type == XML_CDATA_SECTION_NODE)) {
10337                         list =
10338                             xmlHashLookup2(triage, BAD_CAST "#text", NULL);
10339                     } else if (node->type == XML_ELEMENT_NODE) {
10340                         if (node->ns != NULL) {
10341                             list = xmlHashLookup2(triage, node->name,
10342                                                   node->ns->href);
10343                             if (list == NULL)
10344                                 list =
10345                                     xmlHashLookup2(triage, BAD_CAST "#any",
10346                                                    node->ns->href);
10347                         } else
10348                             list =
10349                                 xmlHashLookup2(triage, node->name, NULL);
10350                         if (list == NULL)
10351                             list =
10352                                 xmlHashLookup2(triage, BAD_CAST "#any",
10353                                                NULL);
10354                     }
10355                     if (list == NULL) {
10356                         ret = -1;
10357                         VALID_ERR2(XML_RELAXNG_ERR_ELEMWRONG, node->name);
10358                         break;
10359                     }
10360                     ret = xmlRelaxNGValidateDefinition(ctxt, list);
10361                     if (ret == 0) {
10362                     }
10363                     break;
10364                 }
10365
10366                 list = define->content;
10367                 oldflags = ctxt->flags;
10368                 ctxt->flags |= FLAGS_IGNORABLE;
10369
10370                 while (list != NULL) {
10371                     oldstate = xmlRelaxNGCopyValidState(ctxt, ctxt->state);
10372                     ret = xmlRelaxNGValidateDefinition(ctxt, list);
10373                     if (ret == 0) {
10374                         if (states == NULL) {
10375                             states = xmlRelaxNGNewStates(ctxt, 1);
10376                         }
10377                         if (ctxt->state != NULL) {
10378                             xmlRelaxNGAddStates(ctxt, states, ctxt->state);
10379                         } else if (ctxt->states != NULL) {
10380                             for (i = 0; i < ctxt->states->nbState; i++) {
10381                                 xmlRelaxNGAddStates(ctxt, states,
10382                                                     ctxt->states->
10383                                                     tabState[i]);
10384                             }
10385                             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10386                             ctxt->states = NULL;
10387                         }
10388                     } else {
10389                         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10390                     }
10391                     ctxt->state = oldstate;
10392                     list = list->next;
10393                 }
10394                 if (states != NULL) {
10395                     xmlRelaxNGFreeValidState(ctxt, oldstate);
10396                     ctxt->states = states;
10397                     ctxt->state = NULL;
10398                     ret = 0;
10399                 } else {
10400                     ctxt->states = NULL;
10401                 }
10402                 ctxt->flags = oldflags;
10403                 if (ret != 0) {
10404                     if ((ctxt->flags & FLAGS_IGNORABLE) == 0) {
10405                         xmlRelaxNGDumpValidError(ctxt);
10406                     }
10407                 } else {
10408                     if (ctxt->errNr > errNr)
10409                         xmlRelaxNGPopErrors(ctxt, errNr);
10410                 }
10411                 break;
10412             }
10413         case XML_RELAXNG_DEF:
10414         case XML_RELAXNG_GROUP:
10415             ret = xmlRelaxNGValidateDefinitionList(ctxt, define->content);
10416             break;
10417         case XML_RELAXNG_INTERLEAVE:
10418             ret = xmlRelaxNGValidateInterleave(ctxt, define);
10419             break;
10420         case XML_RELAXNG_ATTRIBUTE:
10421             ret = xmlRelaxNGValidateAttribute(ctxt, define);
10422             break;
10423         case XML_RELAXNG_START:
10424         case XML_RELAXNG_NOOP:
10425         case XML_RELAXNG_REF:
10426         case XML_RELAXNG_EXTERNALREF:
10427         case XML_RELAXNG_PARENTREF:
10428             ret = xmlRelaxNGValidateDefinition(ctxt, define->content);
10429             break;
10430         case XML_RELAXNG_DATATYPE:{
10431                 xmlNodePtr child;
10432                 xmlChar *content = NULL;
10433
10434                 child = node;
10435                 while (child != NULL) {
10436                     if (child->type == XML_ELEMENT_NODE) {
10437                         VALID_ERR2(XML_RELAXNG_ERR_DATAELEM,
10438                                    node->parent->name);
10439                         ret = -1;
10440                         break;
10441                     } else if ((child->type == XML_TEXT_NODE) ||
10442                                (child->type == XML_CDATA_SECTION_NODE)) {
10443                         content = xmlStrcat(content, child->content);
10444                     }
10445                     /* TODO: handle entities ... */
10446                     child = child->next;
10447                 }
10448                 if (ret == -1) {
10449                     if (content != NULL)
10450                         xmlFree(content);
10451                     break;
10452                 }
10453                 if (content == NULL) {
10454                     content = xmlStrdup(BAD_CAST "");
10455                     if (content == NULL) {
10456                         xmlRngVErrMemory(ctxt, "validating\n");
10457                         ret = -1;
10458                         break;
10459                     }
10460                 }
10461                 ret = xmlRelaxNGValidateDatatype(ctxt, content, define,
10462                                                  ctxt->state->seq);
10463                 if (ret == -1) {
10464                     VALID_ERR2(XML_RELAXNG_ERR_DATATYPE, define->name);
10465                 } else if (ret == 0) {
10466                     ctxt->state->seq = NULL;
10467                 }
10468                 if (content != NULL)
10469                     xmlFree(content);
10470                 break;
10471             }
10472         case XML_RELAXNG_VALUE:{
10473                 xmlChar *content = NULL;
10474                 xmlChar *oldvalue;
10475                 xmlNodePtr child;
10476
10477                 child = node;
10478                 while (child != NULL) {
10479                     if (child->type == XML_ELEMENT_NODE) {
10480                         VALID_ERR2(XML_RELAXNG_ERR_VALELEM,
10481                                    node->parent->name);
10482                         ret = -1;
10483                         break;
10484                     } else if ((child->type == XML_TEXT_NODE) ||
10485                                (child->type == XML_CDATA_SECTION_NODE)) {
10486                         content = xmlStrcat(content, child->content);
10487                     }
10488                     /* TODO: handle entities ... */
10489                     child = child->next;
10490                 }
10491                 if (ret == -1) {
10492                     if (content != NULL)
10493                         xmlFree(content);
10494                     break;
10495                 }
10496                 if (content == NULL) {
10497                     content = xmlStrdup(BAD_CAST "");
10498                     if (content == NULL) {
10499                         xmlRngVErrMemory(ctxt, "validating\n");
10500                         ret = -1;
10501                         break;
10502                     }
10503                 }
10504                 oldvalue = ctxt->state->value;
10505                 ctxt->state->value = content;
10506                 ret = xmlRelaxNGValidateValue(ctxt, define);
10507                 ctxt->state->value = oldvalue;
10508                 if (ret == -1) {
10509                     VALID_ERR2(XML_RELAXNG_ERR_VALUE, define->name);
10510                 } else if (ret == 0) {
10511                     ctxt->state->seq = NULL;
10512                 }
10513                 if (content != NULL)
10514                     xmlFree(content);
10515                 break;
10516             }
10517         case XML_RELAXNG_LIST:{
10518                 xmlChar *content;
10519                 xmlNodePtr child;
10520                 xmlChar *oldvalue, *oldendvalue;
10521                 int len;
10522
10523                 /*
10524                  * Make sure it's only text nodes
10525                  */
10526
10527                 content = NULL;
10528                 child = node;
10529                 while (child != NULL) {
10530                     if (child->type == XML_ELEMENT_NODE) {
10531                         VALID_ERR2(XML_RELAXNG_ERR_LISTELEM,
10532                                    node->parent->name);
10533                         ret = -1;
10534                         break;
10535                     } else if ((child->type == XML_TEXT_NODE) ||
10536                                (child->type == XML_CDATA_SECTION_NODE)) {
10537                         content = xmlStrcat(content, child->content);
10538                     }
10539                     /* TODO: handle entities ... */
10540                     child = child->next;
10541                 }
10542                 if (ret == -1) {
10543                     if (content != NULL)
10544                         xmlFree(content);
10545                     break;
10546                 }
10547                 if (content == NULL) {
10548                     content = xmlStrdup(BAD_CAST "");
10549                     if (content == NULL) {
10550                         xmlRngVErrMemory(ctxt, "validating\n");
10551                         ret = -1;
10552                         break;
10553                     }
10554                 }
10555                 len = xmlStrlen(content);
10556                 oldvalue = ctxt->state->value;
10557                 oldendvalue = ctxt->state->endvalue;
10558                 ctxt->state->value = content;
10559                 ctxt->state->endvalue = content + len;
10560                 ret = xmlRelaxNGValidateValue(ctxt, define);
10561                 ctxt->state->value = oldvalue;
10562                 ctxt->state->endvalue = oldendvalue;
10563                 if (ret == -1) {
10564                     VALID_ERR(XML_RELAXNG_ERR_LIST);
10565                 } else if ((ret == 0) && (node != NULL)) {
10566                     ctxt->state->seq = node->next;
10567                 }
10568                 if (content != NULL)
10569                     xmlFree(content);
10570                 break;
10571             }
10572         case XML_RELAXNG_EXCEPT:
10573         case XML_RELAXNG_PARAM:
10574             TODO ret = -1;
10575             break;
10576     }
10577     ctxt->depth--;
10578 #ifdef DEBUG
10579     for (i = 0; i < ctxt->depth; i++)
10580         xmlGenericError(xmlGenericErrorContext, " ");
10581     xmlGenericError(xmlGenericErrorContext,
10582                     "Validating %s ", xmlRelaxNGDefName(define));
10583     if (define->name != NULL)
10584         xmlGenericError(xmlGenericErrorContext, "%s ", define->name);
10585     if (ret == 0)
10586         xmlGenericError(xmlGenericErrorContext, "suceeded\n");
10587     else
10588         xmlGenericError(xmlGenericErrorContext, "failed\n");
10589 #endif
10590     return (ret);
10591 }
10592
10593 /**
10594  * xmlRelaxNGValidateDefinition:
10595  * @ctxt:  a Relax-NG validation context
10596  * @define:  the definition to verify
10597  *
10598  * Validate the current node lists against the definition
10599  *
10600  * Returns 0 if the validation succeeded or an error code.
10601  */
10602 static int
10603 xmlRelaxNGValidateDefinition(xmlRelaxNGValidCtxtPtr ctxt,
10604                              xmlRelaxNGDefinePtr define)
10605 {
10606     xmlRelaxNGStatesPtr states, res;
10607     int i, j, k, ret, oldflags;
10608
10609     /*
10610      * We should NOT have both ctxt->state and ctxt->states
10611      */
10612     if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10613         TODO xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10614         ctxt->state = NULL;
10615     }
10616
10617     if ((ctxt->states == NULL) || (ctxt->states->nbState == 1)) {
10618         if (ctxt->states != NULL) {
10619             ctxt->state = ctxt->states->tabState[0];
10620             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10621             ctxt->states = NULL;
10622         }
10623         ret = xmlRelaxNGValidateState(ctxt, define);
10624         if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10625             TODO xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10626             ctxt->state = NULL;
10627         }
10628         if ((ctxt->states != NULL) && (ctxt->states->nbState == 1)) {
10629             ctxt->state = ctxt->states->tabState[0];
10630             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10631             ctxt->states = NULL;
10632         }
10633         return (ret);
10634     }
10635
10636     states = ctxt->states;
10637     ctxt->states = NULL;
10638     res = NULL;
10639     j = 0;
10640     oldflags = ctxt->flags;
10641     ctxt->flags |= FLAGS_IGNORABLE;
10642     for (i = 0; i < states->nbState; i++) {
10643         ctxt->state = states->tabState[i];
10644         ctxt->states = NULL;
10645         ret = xmlRelaxNGValidateState(ctxt, define);
10646         /*
10647          * We should NOT have both ctxt->state and ctxt->states
10648          */
10649         if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10650             TODO xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10651             ctxt->state = NULL;
10652         }
10653         if (ret == 0) {
10654             if (ctxt->states == NULL) {
10655                 if (res != NULL) {
10656                     /* add the state to the container */
10657                     xmlRelaxNGAddStates(ctxt, res, ctxt->state);
10658                     ctxt->state = NULL;
10659                 } else {
10660                     /* add the state directly in states */
10661                     states->tabState[j++] = ctxt->state;
10662                     ctxt->state = NULL;
10663                 }
10664             } else {
10665                 if (res == NULL) {
10666                     /* make it the new container and copy other results */
10667                     res = ctxt->states;
10668                     ctxt->states = NULL;
10669                     for (k = 0; k < j; k++)
10670                         xmlRelaxNGAddStates(ctxt, res,
10671                                             states->tabState[k]);
10672                 } else {
10673                     /* add all the new results to res and reff the container */
10674                     for (k = 0; k < ctxt->states->nbState; k++)
10675                         xmlRelaxNGAddStates(ctxt, res,
10676                                             ctxt->states->tabState[k]);
10677                     xmlRelaxNGFreeStates(ctxt, ctxt->states);
10678                     ctxt->states = NULL;
10679                 }
10680             }
10681         } else {
10682             if (ctxt->state != NULL) {
10683                 xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10684                 ctxt->state = NULL;
10685             } else if (ctxt->states != NULL) {
10686                 for (k = 0; k < ctxt->states->nbState; k++)
10687                     xmlRelaxNGFreeValidState(ctxt,
10688                                              ctxt->states->tabState[k]);
10689                 xmlRelaxNGFreeStates(ctxt, ctxt->states);
10690                 ctxt->states = NULL;
10691             }
10692         }
10693     }
10694     ctxt->flags = oldflags;
10695     if (res != NULL) {
10696         xmlRelaxNGFreeStates(ctxt, states);
10697         ctxt->states = res;
10698         ret = 0;
10699     } else if (j > 1) {
10700         states->nbState = j;
10701         ctxt->states = states;
10702         ret = 0;
10703     } else if (j == 1) {
10704         ctxt->state = states->tabState[0];
10705         xmlRelaxNGFreeStates(ctxt, states);
10706         ret = 0;
10707     } else {
10708         ret = -1;
10709         xmlRelaxNGFreeStates(ctxt, states);
10710         if (ctxt->states != NULL) {
10711             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10712             ctxt->states = NULL;
10713         }
10714     }
10715     if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10716         TODO xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10717         ctxt->state = NULL;
10718     }
10719     return (ret);
10720 }
10721
10722 /**
10723  * xmlRelaxNGValidateDocument:
10724  * @ctxt:  a Relax-NG validation context
10725  * @doc:  the document
10726  *
10727  * Validate the given document
10728  *
10729  * Returns 0 if the validation succeeded or an error code.
10730  */
10731 static int
10732 xmlRelaxNGValidateDocument(xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc)
10733 {
10734     int ret;
10735     xmlRelaxNGPtr schema;
10736     xmlRelaxNGGrammarPtr grammar;
10737     xmlRelaxNGValidStatePtr state;
10738     xmlNodePtr node;
10739
10740     if ((ctxt == NULL) || (ctxt->schema == NULL) || (doc == NULL))
10741         return (-1);
10742
10743     ctxt->errNo = XML_RELAXNG_OK;
10744     schema = ctxt->schema;
10745     grammar = schema->topgrammar;
10746     if (grammar == NULL) {
10747         VALID_ERR(XML_RELAXNG_ERR_NOGRAMMAR);
10748         return (-1);
10749     }
10750     state = xmlRelaxNGNewValidState(ctxt, NULL);
10751     ctxt->state = state;
10752     ret = xmlRelaxNGValidateDefinition(ctxt, grammar->start);
10753     if ((ctxt->state != NULL) && (state->seq != NULL)) {
10754         state = ctxt->state;
10755         node = state->seq;
10756         node = xmlRelaxNGSkipIgnored(ctxt, node);
10757         if (node != NULL) {
10758             if (ret != -1) {
10759                 VALID_ERR(XML_RELAXNG_ERR_EXTRADATA);
10760                 ret = -1;
10761             }
10762         }
10763     } else if (ctxt->states != NULL) {
10764         int i;
10765         int tmp = -1;
10766
10767         for (i = 0; i < ctxt->states->nbState; i++) {
10768             state = ctxt->states->tabState[i];
10769             node = state->seq;
10770             node = xmlRelaxNGSkipIgnored(ctxt, node);
10771             if (node == NULL)
10772                 tmp = 0;
10773             xmlRelaxNGFreeValidState(ctxt, state);
10774         }
10775         if (tmp == -1) {
10776             if (ret != -1) {
10777                 VALID_ERR(XML_RELAXNG_ERR_EXTRADATA);
10778                 ret = -1;
10779             }
10780         }
10781     }
10782     if (ctxt->state != NULL) {
10783         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10784         ctxt->state = NULL;
10785     }
10786     if (ret != 0)
10787         xmlRelaxNGDumpValidError(ctxt);
10788 #ifdef DEBUG
10789     else if (ctxt->errNr != 0) {
10790         ctxt->error(ctxt->userData,
10791                     "%d Extra error messages left on stack !\n",
10792                     ctxt->errNr);
10793         xmlRelaxNGDumpValidError(ctxt);
10794     }
10795 #endif
10796 #ifdef LIBXML_VALID_ENABLED
10797     if (ctxt->idref == 1) {
10798         xmlValidCtxt vctxt;
10799
10800         memset(&vctxt, 0, sizeof(xmlValidCtxt));
10801         vctxt.valid = 1;
10802         vctxt.error = ctxt->error;
10803         vctxt.warning = ctxt->warning;
10804         vctxt.userData = ctxt->userData;
10805
10806         if (xmlValidateDocumentFinal(&vctxt, doc) != 1)
10807             ret = -1;
10808     }
10809 #endif /* LIBXML_VALID_ENABLED */
10810     if ((ret == 0) && (ctxt->errNo != XML_RELAXNG_OK))
10811         ret = -1;
10812
10813     return (ret);
10814 }
10815
10816 /**
10817  * xmlRelaxNGCleanPSVI:
10818  * @node:  an input element or document
10819  *
10820  * Call this routine to speed up XPath computation on static documents.
10821  * This stamps all the element nodes with the document order
10822  * Like for line information, the order is kept in the element->content
10823  * field, the value stored is actually - the node number (starting at -1)
10824  * to be able to differentiate from line numbers.
10825  *
10826  * Returns the number of elements found in the document or -1 in case
10827  *    of error.
10828  */
10829 static void
10830 xmlRelaxNGCleanPSVI(xmlNodePtr node) {
10831     xmlNodePtr cur;
10832
10833     if ((node == NULL) ||
10834         ((node->type != XML_ELEMENT_NODE) &&
10835          (node->type != XML_DOCUMENT_NODE) &&
10836          (node->type != XML_HTML_DOCUMENT_NODE)))
10837         return;
10838     if (node->type == XML_ELEMENT_NODE)
10839         node->psvi = NULL;
10840
10841     cur = node->children;
10842     while (cur != NULL) {
10843         if (cur->type == XML_ELEMENT_NODE) {
10844             cur->psvi = NULL;
10845             if (cur->children != NULL) {
10846                 cur = cur->children;
10847                 continue;
10848             }
10849         }
10850         if (cur->next != NULL) {
10851             cur = cur->next;
10852             continue;
10853         }
10854         do {
10855             cur = cur->parent;
10856             if (cur == NULL)
10857                 break;
10858             if (cur == node) {
10859                 cur = NULL;
10860                 break;
10861             }
10862             if (cur->next != NULL) {
10863                 cur = cur->next;
10864                 break;
10865             }
10866         } while (cur != NULL);
10867     }
10868     return;
10869 }
10870 /************************************************************************
10871  *                                                                      *
10872  *                      Validation interfaces                           *
10873  *                                                                      *
10874  ************************************************************************/
10875
10876 /**
10877  * xmlRelaxNGNewValidCtxt:
10878  * @schema:  a precompiled XML RelaxNGs
10879  *
10880  * Create an XML RelaxNGs validation context based on the given schema
10881  *
10882  * Returns the validation context or NULL in case of error
10883  */
10884 xmlRelaxNGValidCtxtPtr
10885 xmlRelaxNGNewValidCtxt(xmlRelaxNGPtr schema)
10886 {
10887     xmlRelaxNGValidCtxtPtr ret;
10888
10889     ret = (xmlRelaxNGValidCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGValidCtxt));
10890     if (ret == NULL) {
10891         xmlRngVErrMemory(NULL, "building context\n");
10892         return (NULL);
10893     }
10894     memset(ret, 0, sizeof(xmlRelaxNGValidCtxt));
10895     ret->schema = schema;
10896     ret->error = xmlGenericError;
10897     ret->userData = xmlGenericErrorContext;
10898     ret->errNr = 0;
10899     ret->errMax = 0;
10900     ret->err = NULL;
10901     ret->errTab = NULL;
10902     if (schema != NULL)
10903         ret->idref = schema->idref;
10904     ret->states = NULL;
10905     ret->freeState = NULL;
10906     ret->freeStates = NULL;
10907     ret->errNo = XML_RELAXNG_OK;
10908     return (ret);
10909 }
10910
10911 /**
10912  * xmlRelaxNGFreeValidCtxt:
10913  * @ctxt:  the schema validation context
10914  *
10915  * Free the resources associated to the schema validation context
10916  */
10917 void
10918 xmlRelaxNGFreeValidCtxt(xmlRelaxNGValidCtxtPtr ctxt)
10919 {
10920     int k;
10921
10922     if (ctxt == NULL)
10923         return;
10924     if (ctxt->states != NULL)
10925         xmlRelaxNGFreeStates(NULL, ctxt->states);
10926     if (ctxt->freeState != NULL) {
10927         for (k = 0; k < ctxt->freeState->nbState; k++) {
10928             xmlRelaxNGFreeValidState(NULL, ctxt->freeState->tabState[k]);
10929         }
10930         xmlRelaxNGFreeStates(NULL, ctxt->freeState);
10931     }
10932     if (ctxt->freeStates != NULL) {
10933         for (k = 0; k < ctxt->freeStatesNr; k++) {
10934             xmlRelaxNGFreeStates(NULL, ctxt->freeStates[k]);
10935         }
10936         xmlFree(ctxt->freeStates);
10937     }
10938     if (ctxt->errTab != NULL)
10939         xmlFree(ctxt->errTab);
10940     if (ctxt->elemTab != NULL) {
10941         xmlRegExecCtxtPtr exec;
10942
10943         exec = xmlRelaxNGElemPop(ctxt);
10944         while (exec != NULL) {
10945             xmlRegFreeExecCtxt(exec);
10946             exec = xmlRelaxNGElemPop(ctxt);
10947         }
10948         xmlFree(ctxt->elemTab);
10949     }
10950     xmlFree(ctxt);
10951 }
10952
10953 /**
10954  * xmlRelaxNGSetValidErrors:
10955  * @ctxt:  a Relax-NG validation context
10956  * @err:  the error function
10957  * @warn: the warning function
10958  * @ctx: the functions context
10959  *
10960  * Set the error and warning callback informations
10961  */
10962 void
10963 xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
10964                          xmlRelaxNGValidityErrorFunc err,
10965                          xmlRelaxNGValidityWarningFunc warn, void *ctx)
10966 {
10967     if (ctxt == NULL)
10968         return;
10969     ctxt->error = err;
10970     ctxt->warning = warn;
10971     ctxt->userData = ctx;
10972     ctxt->serror = NULL;
10973 }
10974
10975 /**
10976  * xmlRelaxNGSetValidStructuredErrors:
10977  * @ctxt:  a Relax-NG validation context
10978  * @serror:  the structured error function
10979  * @ctx: the functions context
10980  *
10981  * Set the structured error callback
10982  */
10983 void
10984 xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt,
10985                                    xmlStructuredErrorFunc serror, void *ctx)
10986 {
10987     if (ctxt == NULL)
10988         return;
10989     ctxt->serror = serror;
10990     ctxt->error = NULL;
10991     ctxt->warning = NULL;
10992     ctxt->userData = ctx;
10993 }
10994
10995 /**
10996  * xmlRelaxNGGetValidErrors:
10997  * @ctxt:  a Relax-NG validation context
10998  * @err:  the error function result
10999  * @warn: the warning function result
11000  * @ctx: the functions context result
11001  *
11002  * Get the error and warning callback informations
11003  *
11004  * Returns -1 in case of error and 0 otherwise
11005  */
11006 int
11007 xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
11008                          xmlRelaxNGValidityErrorFunc * err,
11009                          xmlRelaxNGValidityWarningFunc * warn, void **ctx)
11010 {
11011     if (ctxt == NULL)
11012         return (-1);
11013     if (err != NULL)
11014         *err = ctxt->error;
11015     if (warn != NULL)
11016         *warn = ctxt->warning;
11017     if (ctx != NULL)
11018         *ctx = ctxt->userData;
11019     return (0);
11020 }
11021
11022 /**
11023  * xmlRelaxNGValidateDoc:
11024  * @ctxt:  a Relax-NG validation context
11025  * @doc:  a parsed document tree
11026  *
11027  * Validate a document tree in memory.
11028  *
11029  * Returns 0 if the document is valid, a positive error code
11030  *     number otherwise and -1 in case of internal or API error.
11031  */
11032 int
11033 xmlRelaxNGValidateDoc(xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc)
11034 {
11035     int ret;
11036
11037     if ((ctxt == NULL) || (doc == NULL))
11038         return (-1);
11039
11040     ctxt->doc = doc;
11041
11042     ret = xmlRelaxNGValidateDocument(ctxt, doc);
11043     /*
11044      * Remove all left PSVI
11045      */
11046     xmlRelaxNGCleanPSVI((xmlNodePtr) doc);
11047
11048     /*
11049      * TODO: build error codes
11050      */
11051     if (ret == -1)
11052         return (1);
11053     return (ret);
11054 }
11055
11056 #define bottom_relaxng
11057 #include "elfgcchack.h"
11058 #endif /* LIBXML_SCHEMAS_ENABLED */