relaxng.c 357 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * relaxng.c : implementation of the Relax-NG handling and validity checking
 *
 * See Copyright for the status of this software.
 *
 * Daniel Veillard <veillard@redhat.com>
 */

9 10
/**
 * TODO:
11 12
 * - add support for DTD compatibility spec
 *   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 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#define IN_LIBXML
#include "libxml.h"

#ifdef LIBXML_SCHEMAS_ENABLED

#include <string.h>
#include <stdio.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/hash.h>
#include <libxml/uri.h>

#include <libxml/relaxng.h>

#include <libxml/xmlschemastypes.h>
#include <libxml/xmlautomata.h>
#include <libxml/xmlregexp.h>
34
#include <libxml/xmlschemastypes.h>
35 36 37 38 39 40 41

/*
 * The Relax-NG namespace
 */
static const xmlChar *xmlRelaxNGNs = (const xmlChar *)
    "http://relaxng.org/ns/structure/1.0";

42
#define IS_RELAXNG(node, typ)						\
43
   ((node != NULL) && (node->ns != NULL) &&				\
44 45
    (node->type == XML_ELEMENT_NODE) &&					\
    (xmlStrEqual(node->name, (const xmlChar *) typ)) &&		\
46 47 48
    (xmlStrEqual(node->ns->href, xmlRelaxNGNs)))


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 71
#define DEBUG_PROGRESSIVE 1
#endif
72

73 74
#define MAX_ERROR 5

75
#define TODO								\
76 77 78 79 80 81 82 83 84 85
    xmlGenericError(xmlGenericErrorContext,				\
	    "Unimplemented block at %s:%d\n",				\
            __FILE__, __LINE__);

typedef struct _xmlRelaxNGSchema xmlRelaxNGSchema;
typedef xmlRelaxNGSchema *xmlRelaxNGSchemaPtr;

typedef struct _xmlRelaxNGDefine xmlRelaxNGDefine;
typedef xmlRelaxNGDefine *xmlRelaxNGDefinePtr;

86 87 88
typedef struct _xmlRelaxNGDocument xmlRelaxNGDocument;
typedef xmlRelaxNGDocument *xmlRelaxNGDocumentPtr;

89 90 91
typedef struct _xmlRelaxNGInclude xmlRelaxNGInclude;
typedef xmlRelaxNGInclude *xmlRelaxNGIncludePtr;

92
typedef enum {
93 94 95
    XML_RELAXNG_COMBINE_UNDEFINED = 0,  /* undefined */
    XML_RELAXNG_COMBINE_CHOICE, /* choice */
    XML_RELAXNG_COMBINE_INTERLEAVE      /* interleave */
96 97
} xmlRelaxNGCombine;

98 99 100 101 102 103 104
typedef enum {
    XML_RELAXNG_CONTENT_ERROR = -1,
    XML_RELAXNG_CONTENT_EMPTY = 0,
    XML_RELAXNG_CONTENT_SIMPLE,
    XML_RELAXNG_CONTENT_COMPLEX
} xmlRelaxNGContentType;

105 106 107 108
typedef struct _xmlRelaxNGGrammar xmlRelaxNGGrammar;
typedef xmlRelaxNGGrammar *xmlRelaxNGGrammarPtr;

struct _xmlRelaxNGGrammar {
109 110 111 112 113 114 115 116
    xmlRelaxNGGrammarPtr parent;        /* the parent grammar if any */
    xmlRelaxNGGrammarPtr children;      /* the children grammar if any */
    xmlRelaxNGGrammarPtr next;  /* the next grammar if any */
    xmlRelaxNGDefinePtr start;  /* <start> content */
    xmlRelaxNGCombine combine;  /* the default combine value */
    xmlRelaxNGDefinePtr startList;      /* list of <start> definitions */
    xmlHashTablePtr defs;       /* define* */
    xmlHashTablePtr refs;       /* references */
117 118 119 120
};


typedef enum {
121 122
    XML_RELAXNG_NOOP = -1,      /* a no operation from simplification  */
    XML_RELAXNG_EMPTY = 0,      /* an empty pattern */
123
    XML_RELAXNG_NOT_ALLOWED,    /* not allowed top */
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    XML_RELAXNG_EXCEPT,         /* except present in nameclass defs */
    XML_RELAXNG_TEXT,           /* textual content */
    XML_RELAXNG_ELEMENT,        /* an element */
    XML_RELAXNG_DATATYPE,       /* extenal data type definition */
    XML_RELAXNG_PARAM,          /* extenal data type parameter */
    XML_RELAXNG_VALUE,          /* value from an extenal data type definition */
    XML_RELAXNG_LIST,           /* a list of patterns */
    XML_RELAXNG_ATTRIBUTE,      /* an attrbute following a pattern */
    XML_RELAXNG_DEF,            /* a definition */
    XML_RELAXNG_REF,            /* reference to a definition */
    XML_RELAXNG_EXTERNALREF,    /* reference to an external def */
    XML_RELAXNG_PARENTREF,      /* reference to a def in the parent grammar */
    XML_RELAXNG_OPTIONAL,       /* optional patterns */
    XML_RELAXNG_ZEROORMORE,     /* zero or more non empty patterns */
    XML_RELAXNG_ONEORMORE,      /* one or more non empty patterns */
    XML_RELAXNG_CHOICE,         /* a choice between non empty patterns */
    XML_RELAXNG_GROUP,          /* a pair/group of non empty patterns */
    XML_RELAXNG_INTERLEAVE,     /* interleaving choice of non-empty patterns */
    XML_RELAXNG_START           /* Used to keep track of starts on grammars */
143 144
} xmlRelaxNGType;

145 146 147 148 149 150 151 152
#define IS_NULLABLE		(1 << 0)
#define IS_NOT_NULLABLE		(1 << 1)
#define IS_INDETERMINIST	(1 << 2)
#define IS_MIXED		(1 << 3)
#define IS_TRIABLE		(1 << 4)
#define IS_PROCESSED		(1 << 5)
#define IS_COMPILABLE		(1 << 6)
#define IS_NOT_COMPILABLE	(1 << 7)
153
#define IS_EXTERNAL_REF	        (1 << 8)
154

155
struct _xmlRelaxNGDefine {
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    xmlRelaxNGType type;        /* the type of definition */
    xmlNodePtr node;            /* the node in the source */
    xmlChar *name;              /* the element local name if present */
    xmlChar *ns;                /* the namespace local name if present */
    xmlChar *value;             /* value when available */
    void *data;                 /* data lib or specific pointer */
    xmlRelaxNGDefinePtr content;        /* the expected content */
    xmlRelaxNGDefinePtr parent; /* the parent definition, if any */
    xmlRelaxNGDefinePtr next;   /* list within grouping sequences */
    xmlRelaxNGDefinePtr attrs;  /* list of attributes for elements */
    xmlRelaxNGDefinePtr nameClass;      /* the nameClass definition if any */
    xmlRelaxNGDefinePtr nextHash;       /* next define in defs/refs hash tables */
    short depth;                /* used for the cycle detection */
    short dflags;               /* define related flags */
    xmlRegexpPtr contModel;     /* a compiled content model if available */
171 172 173 174 175 176 177 178
};

/**
 * _xmlRelaxNG:
 *
 * A RelaxNGs definition
 */
struct _xmlRelaxNG {
179
    void *_private;             /* unused by the library for users or bindings */
180 181 182
    xmlRelaxNGGrammarPtr topgrammar;
    xmlDocPtr doc;

183
    int idref;                  /* requires idref checking */
184

185 186 187 188 189 190
    xmlHashTablePtr defs;       /* define */
    xmlHashTablePtr refs;       /* references */
    xmlRelaxNGDocumentPtr documents;    /* all the documents loaded */
    xmlRelaxNGIncludePtr includes;      /* all the includes loaded */
    int defNr;                  /* number of defines used */
    xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
191

192 193
};

194 195 196 197 198 199 200 201
#define XML_RELAXNG_IN_ATTRIBUTE	(1 << 0)
#define XML_RELAXNG_IN_ONEORMORE	(1 << 1)
#define XML_RELAXNG_IN_LIST		(1 << 2)
#define XML_RELAXNG_IN_DATAEXCEPT	(1 << 3)
#define XML_RELAXNG_IN_START		(1 << 4)
#define XML_RELAXNG_IN_OOMGROUP		(1 << 5)
#define XML_RELAXNG_IN_OOMINTERLEAVE	(1 << 6)
#define XML_RELAXNG_IN_EXTERNALREF	(1 << 7)
202 203
#define XML_RELAXNG_IN_ANYEXCEPT	(1 << 8)
#define XML_RELAXNG_IN_NSEXCEPT		(1 << 9)
204 205

struct _xmlRelaxNGParserCtxt {
206 207 208
    void *userData;             /* user specific data block */
    xmlRelaxNGValidityErrorFunc error;  /* the callback in case of errors */
    xmlRelaxNGValidityWarningFunc warning;      /* the callback in case of warning */
209
    xmlStructuredErrorFunc serror;
210
    xmlRelaxNGValidErr err;
211

212 213 214 215 216 217 218 219
    xmlRelaxNGPtr schema;       /* The schema in use */
    xmlRelaxNGGrammarPtr grammar;       /* the current grammar */
    xmlRelaxNGGrammarPtr parentgrammar; /* the parent grammar */
    int flags;                  /* parser flags */
    int nbErrors;               /* number of errors at parse time */
    int nbWarnings;             /* number of warnings at parse time */
    const xmlChar *define;      /* the current define scope */
    xmlRelaxNGDefinePtr def;    /* the current define */
220

221 222
    int nbInterleaves;
    xmlHashTablePtr interleaves;        /* keep track of all the interleaves */
223

224 225 226 227
    xmlRelaxNGDocumentPtr documents;    /* all the documents loaded */
    xmlRelaxNGIncludePtr includes;      /* all the includes loaded */
    xmlChar *URL;
    xmlDocPtr document;
228

229 230 231
    int defNr;                  /* number of defines used */
    int defMax;                 /* number of defines aloocated */
    xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
232

233 234
    const char *buffer;
    int size;
235

236
    /* the document stack */
237 238 239 240
    xmlRelaxNGDocumentPtr doc;  /* Current parsed external ref */
    int docNr;                  /* Depth of the parsing stack */
    int docMax;                 /* Max depth of the parsing stack */
    xmlRelaxNGDocumentPtr *docTab;      /* array of docs */
241 242

    /* the include stack */
243 244 245 246
    xmlRelaxNGIncludePtr inc;   /* Current parsed include */
    int incNr;                  /* Depth of the include parsing stack */
    int incMax;                 /* Max depth of the parsing stack */
    xmlRelaxNGIncludePtr *incTab;       /* array of incs */
247

248
    int idref;                  /* requires idref checking */
249 250

    /* used to compile content models */
251 252
    xmlAutomataPtr am;          /* the automata */
    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 259
};

#define FLAGS_IGNORABLE		1
#define FLAGS_NEGATIVE		2
260
#define FLAGS_MIXED_CONTENT	4
261
#define FLAGS_NOERROR		8
262

263 264 265 266 267 268 269 270
/**
 * xmlRelaxNGInterleaveGroup:
 *
 * A RelaxNGs partition set associated to lists of definitions
 */
typedef struct _xmlRelaxNGInterleaveGroup xmlRelaxNGInterleaveGroup;
typedef xmlRelaxNGInterleaveGroup *xmlRelaxNGInterleaveGroupPtr;
struct _xmlRelaxNGInterleaveGroup {
271 272 273
    xmlRelaxNGDefinePtr rule;   /* the rule to satisfy */
    xmlRelaxNGDefinePtr *defs;  /* the array of element definitions */
    xmlRelaxNGDefinePtr *attrs; /* the array of attributes definitions */
274 275
};

276 277
#define IS_DETERMINIST		1
#define IS_NEEDCHECK		2
278

279 280 281 282 283 284 285 286
/**
 * xmlRelaxNGPartitions:
 *
 * A RelaxNGs partition associated to an interleave group
 */
typedef struct _xmlRelaxNGPartition xmlRelaxNGPartition;
typedef xmlRelaxNGPartition *xmlRelaxNGPartitionPtr;
struct _xmlRelaxNGPartition {
287 288 289 290
    int nbgroups;               /* number of groups in the partitions */
    xmlHashTablePtr triage;     /* hash table used to direct nodes to the
                                 * right group when possible */
    int flags;                  /* determinist ? */
291 292 293
    xmlRelaxNGInterleaveGroupPtr *groups;
};

294 295 296 297 298 299 300 301 302
/**
 * xmlRelaxNGValidState:
 *
 * A RelaxNGs validation state
 */
#define MAX_ATTR 20
typedef struct _xmlRelaxNGValidState xmlRelaxNGValidState;
typedef xmlRelaxNGValidState *xmlRelaxNGValidStatePtr;
struct _xmlRelaxNGValidState {
303 304 305 306 307 308 309 310
    xmlNodePtr node;            /* the current node */
    xmlNodePtr seq;             /* the sequence of children left to validate */
    int nbAttrs;                /* the number of attributes */
    int maxAttrs;               /* the size of attrs */
    int nbAttrLeft;             /* the number of attributes left to validate */
    xmlChar *value;             /* the value when operating on string */
    xmlChar *endvalue;          /* the end value when operating on string */
    xmlAttrPtr *attrs;          /* the array of attributes */
311 312
};

313 314 315 316 317 318 319 320
/**
 * xmlRelaxNGStates:
 *
 * A RelaxNGs container for validation state
 */
typedef struct _xmlRelaxNGStates xmlRelaxNGStates;
typedef xmlRelaxNGStates *xmlRelaxNGStatesPtr;
struct _xmlRelaxNGStates {
321 322
    int nbState;                /* the number of states */
    int maxState;               /* the size of the array */
323 324 325
    xmlRelaxNGValidStatePtr *tabState;
};

326
#define ERROR_IS_DUP	1
327

328 329 330 331 332 333 334 335
/**
 * xmlRelaxNGValidError:
 *
 * A RelaxNGs validation error
 */
typedef struct _xmlRelaxNGValidError xmlRelaxNGValidError;
typedef xmlRelaxNGValidError *xmlRelaxNGValidErrorPtr;
struct _xmlRelaxNGValidError {
336 337 338 339 340 341
    xmlRelaxNGValidErr err;     /* the error number */
    int flags;                  /* flags */
    xmlNodePtr node;            /* the current node */
    xmlNodePtr seq;             /* the current child */
    const xmlChar *arg1;        /* first arg */
    const xmlChar *arg2;        /* second arg */
342 343
};

344 345 346 347 348 349 350
/**
 * xmlRelaxNGValidCtxt:
 *
 * A RelaxNGs validation context
 */

struct _xmlRelaxNGValidCtxt {
351 352 353
    void *userData;             /* user specific data block */
    xmlRelaxNGValidityErrorFunc error;  /* the callback in case of errors */
    xmlRelaxNGValidityWarningFunc warning;      /* the callback in case of warning */
354
    xmlStructuredErrorFunc serror;
355 356 357 358 359 360 361 362
    int nbErrors;               /* number of errors in validation */

    xmlRelaxNGPtr schema;       /* The schema in use */
    xmlDocPtr doc;              /* the document being validated */
    int flags;                  /* validation flags */
    int depth;                  /* validation depth */
    int idref;                  /* requires idref checking */
    int errNo;                  /* the first error found */
363 364 365 366 367 368

    /*
     * Errors accumulated in branches may have to be stacked to be
     * provided back when it's sure they affect validation.
     */
    xmlRelaxNGValidErrorPtr err;        /* Last error */
369 370 371
    int errNr;                  /* Depth of the error stack */
    int errMax;                 /* Max depth of the error stack */
    xmlRelaxNGValidErrorPtr errTab;     /* stack of errors */
372

373 374
    xmlRelaxNGValidStatePtr state;      /* the current validation state */
    xmlRelaxNGStatesPtr states; /* the accumulated state list */
375

376 377 378 379
    xmlRelaxNGStatesPtr freeState;      /* the pool of free valid states */
    int freeStatesNr;
    int freeStatesMax;
    xmlRelaxNGStatesPtr *freeStates;    /* the pool of free state groups */
380 381 382 383

    /*
     * This is used for "progressive" validation
     */
384 385 386 387 388 389 390 391 392
    xmlRegExecCtxtPtr elem;     /* the current element regexp */
    int elemNr;                 /* the number of element validated */
    int elemMax;                /* the max depth of elements */
    xmlRegExecCtxtPtr *elemTab; /* the stack of regexp runtime */
    int pstate;                 /* progressive state */
    xmlNodePtr pnode;           /* the current node */
    xmlRelaxNGDefinePtr pdef;   /* the non-streamable definition */
    int perr;                   /* signal error in content model
                                 * outside the regexp */
393 394
};

395 396 397 398 399 400
/**
 * xmlRelaxNGInclude:
 *
 * Structure associated to a RelaxNGs document element
 */
struct _xmlRelaxNGInclude {
401 402 403 404 405
    xmlRelaxNGIncludePtr next;  /* keep a chain of includes */
    xmlChar *href;              /* the normalized href value */
    xmlDocPtr doc;              /* the associated XML document */
    xmlRelaxNGDefinePtr content;        /* the definitions */
    xmlRelaxNGPtr schema;       /* the schema */
406 407
};

408 409 410 411 412 413
/**
 * xmlRelaxNGDocument:
 *
 * Structure associated to a RelaxNGs document element
 */
struct _xmlRelaxNGDocument {
414
    xmlRelaxNGDocumentPtr next; /* keep a chain of documents */
415 416 417 418
    xmlChar *href;              /* the normalized href value */
    xmlDocPtr doc;              /* the associated XML document */
    xmlRelaxNGDefinePtr content;        /* the definitions */
    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 431 432 433 434 435 436 437 438
 *									*
 ************************************************************************/

/**
 * xmlRngPErrMemory:
 * @ctxt:  an Relax-NG parser context
 * @extra:  extra informations
 *
 * Handle a redefinition of attribute error
 */
static void
xmlRngPErrMemory(xmlRelaxNGParserCtxtPtr ctxt, const char *extra)
{
439
    xmlStructuredErrorFunc schannel = NULL;
440 441 442 443
    xmlGenericErrorFunc channel = NULL;
    void *data = NULL;

    if (ctxt != NULL) {
444 445 446 447
        if (ctxt->serror != NULL)
	    schannel = ctxt->serror;
	else
	    channel = ctxt->error;
448 449 450 451
        data = ctxt->userData;
        ctxt->nbErrors++;
    }
    if (extra)
452
        __xmlRaiseError(schannel, channel, data,
453 454 455 456 457
                        NULL, NULL, XML_FROM_RELAXNGP,
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
                        NULL, NULL, 0, 0,
                        "Memory allocation failed : %s\n", extra);
    else
458
        __xmlRaiseError(schannel, channel, data,
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
                        NULL, NULL, XML_FROM_RELAXNGP,
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, NULL,
                        NULL, NULL, 0, 0, "Memory allocation failed\n");
}

/**
 * xmlRngVErrMemory:
 * @ctxt:  a Relax-NG validation context
 * @extra:  extra informations
 *
 * Handle a redefinition of attribute error
 */
static void
xmlRngVErrMemory(xmlRelaxNGValidCtxtPtr ctxt, const char *extra)
{
474
    xmlStructuredErrorFunc schannel = NULL;
475 476 477 478
    xmlGenericErrorFunc channel = NULL;
    void *data = NULL;

    if (ctxt != NULL) {
479 480 481 482
        if (ctxt->serror != NULL)
	    schannel = ctxt->serror;
	else
	    channel = ctxt->error;
483 484 485 486
        data = ctxt->userData;
        ctxt->nbErrors++;
    }
    if (extra)
487
        __xmlRaiseError(schannel, channel, data,
488 489 490 491 492
                        NULL, NULL, XML_FROM_RELAXNGV,
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
                        NULL, NULL, 0, 0,
                        "Memory allocation failed : %s\n", extra);
    else
493
        __xmlRaiseError(schannel, channel, data,
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
                        NULL, NULL, XML_FROM_RELAXNGV,
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, NULL,
                        NULL, NULL, 0, 0, "Memory allocation failed\n");
}

/**
 * xmlRngPErr:
 * @ctxt:  a Relax-NG parser context
 * @node:  the node raising the error
 * @error:  the error code
 * @msg:  message
 * @str1:  extra info
 * @str2:  extra info
 *
 * Handle a Relax NG Parsing error
 */
510
static void LIBXML_ATTR_FORMAT(4,0)
511 512 513
xmlRngPErr(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node, int error,
           const char *msg, const xmlChar * str1, const xmlChar * str2)
{
514
    xmlStructuredErrorFunc schannel = NULL;
515 516 517 518
    xmlGenericErrorFunc channel = NULL;
    void *data = NULL;

    if (ctxt != NULL) {
519 520 521 522
        if (ctxt->serror != NULL)
	    schannel = ctxt->serror;
	else
	    channel = ctxt->error;
523 524 525
        data = ctxt->userData;
        ctxt->nbErrors++;
    }
526
    __xmlRaiseError(schannel, channel, data,
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                    NULL, node, XML_FROM_RELAXNGP,
                    error, XML_ERR_ERROR, NULL, 0,
                    (const char *) str1, (const char *) str2, NULL, 0, 0,
                    msg, str1, str2);
}

/**
 * xmlRngVErr:
 * @ctxt:  a Relax-NG validation context
 * @node:  the node raising the error
 * @error:  the error code
 * @msg:  message
 * @str1:  extra info
 * @str2:  extra info
 *
 * Handle a Relax NG Validation error
 */
544
static void LIBXML_ATTR_FORMAT(4,0)
545 546 547
xmlRngVErr(xmlRelaxNGValidCtxtPtr ctxt, xmlNodePtr node, int error,
           const char *msg, const xmlChar * str1, const xmlChar * str2)
{
548
    xmlStructuredErrorFunc schannel = NULL;
549 550 551 552
    xmlGenericErrorFunc channel = NULL;
    void *data = NULL;

    if (ctxt != NULL) {
553 554 555 556
        if (ctxt->serror != NULL)
	    schannel = ctxt->serror;
	else
	    channel = ctxt->error;
557 558 559
        data = ctxt->userData;
        ctxt->nbErrors++;
    }
560
    __xmlRaiseError(schannel, channel, data,
561 562 563 564 565 566
                    NULL, node, XML_FROM_RELAXNGV,
                    error, XML_ERR_ERROR, NULL, 0,
                    (const char *) str1, (const char *) str2, NULL, 0, 0,
                    msg, str1, str2);
}

567
/************************************************************************
568 569 570
 *									*
 *		Preliminary type checking interfaces			*
 *									*
571
 ************************************************************************/
572

573 574 575 576 577 578 579 580 581 582
/**
 * xmlRelaxNGTypeHave:
 * @data:  data needed for the library
 * @type:  the type name
 * @value:  the value to check
 *
 * Function provided by a type library to check if a type is exported
 *
 * Returns 1 if yes, 0 if no and -1 in case of error.
 */
583
typedef int (*xmlRelaxNGTypeHave) (void *data, const xmlChar * type);
584 585 586 587 588 589

/**
 * xmlRelaxNGTypeCheck:
 * @data:  data needed for the library
 * @type:  the type name
 * @value:  the value to check
590
 * @result:  place to store the result if needed
591 592 593 594 595
 *
 * Function provided by a type library to check if a value match a type
 *
 * Returns 1 if yes, 0 if no and -1 in case of error.
 */
596 597 598
typedef int (*xmlRelaxNGTypeCheck) (void *data, const xmlChar * type,
                                    const xmlChar * value, void **result,
                                    xmlNodePtr node);
599 600 601 602 603 604 605 606 607 608 609 610 611 612

/**
 * xmlRelaxNGFacetCheck:
 * @data:  data needed for the library
 * @type:  the type name
 * @facet:  the facet name
 * @val:  the facet value
 * @strval:  the string value
 * @value:  the value to check
 *
 * Function provided by a type library to check a value facet
 *
 * Returns 1 if yes, 0 if no and -1 in case of error.
 */
613 614 615 616
typedef int (*xmlRelaxNGFacetCheck) (void *data, const xmlChar * type,
                                     const xmlChar * facet,
                                     const xmlChar * val,
                                     const xmlChar * strval, void *value);
617 618 619 620 621 622 623 624 625

/**
 * xmlRelaxNGTypeFree:
 * @data:  data needed for the library
 * @result:  the value to free
 *
 * Function provided by a type library to free a returned result
 */
typedef void (*xmlRelaxNGTypeFree) (void *data, void *result);
626 627 628 629 630 631 632 633 634 635 636 637 638

/**
 * xmlRelaxNGTypeCompare:
 * @data:  data needed for the library
 * @type:  the type name
 * @value1:  the first value
 * @value2:  the second value
 *
 * Function provided by a type library to compare two values accordingly
 * to a type.
 *
 * Returns 1 if yes, 0 if no and -1 in case of error.
 */
639 640 641 642 643 644
typedef int (*xmlRelaxNGTypeCompare) (void *data, const xmlChar * type,
                                      const xmlChar * value1,
                                      xmlNodePtr ctxt1,
                                      void *comp1,
                                      const xmlChar * value2,
                                      xmlNodePtr ctxt2);
645 646 647
typedef struct _xmlRelaxNGTypeLibrary xmlRelaxNGTypeLibrary;
typedef xmlRelaxNGTypeLibrary *xmlRelaxNGTypeLibraryPtr;
struct _xmlRelaxNGTypeLibrary {
648 649 650 651 652 653 654
    const xmlChar *namespace;   /* the datatypeLibrary value */
    void *data;                 /* data needed for the library */
    xmlRelaxNGTypeHave have;    /* the export function */
    xmlRelaxNGTypeCheck check;  /* the checking function */
    xmlRelaxNGTypeCompare comp; /* the compare function */
    xmlRelaxNGFacetCheck facet; /* the facet check function */
    xmlRelaxNGTypeFree freef;   /* the freeing function */
655 656
};

657
/************************************************************************
658 659 660
 *									*
 *			Allocation functions				*
 *									*
661 662 663
 ************************************************************************/
static void xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar);
static void xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define);
664
static void xmlRelaxNGNormExtSpace(xmlChar * value);
665
static void xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema);
666 667 668 669
static int xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt
                                     ATTRIBUTE_UNUSED,
                                     xmlRelaxNGValidStatePtr state1,
                                     xmlRelaxNGValidStatePtr state2);
670
static void xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,
671
                                     xmlRelaxNGValidStatePtr state);
672

673 674 675 676 677 678 679 680 681 682 683 684 685
/**
 * xmlRelaxNGFreeDocument:
 * @docu:  a document structure
 *
 * Deallocate a RelaxNG document structure.
 */
static void
xmlRelaxNGFreeDocument(xmlRelaxNGDocumentPtr docu)
{
    if (docu == NULL)
        return;

    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 692 693
    xmlFree(docu);
}

694 695 696 697 698 699 700 701 702 703
/**
 * xmlRelaxNGFreeDocumentList:
 * @docu:  a list of  document structure
 *
 * Deallocate a RelaxNG document structures.
 */
static void
xmlRelaxNGFreeDocumentList(xmlRelaxNGDocumentPtr docu)
{
    xmlRelaxNGDocumentPtr next;
704

705
    while (docu != NULL) {
706 707 708
        next = docu->next;
        xmlRelaxNGFreeDocument(docu);
        docu = next;
709 710 711
    }
}

712 713 714 715 716 717 718 719 720 721 722 723 724
/**
 * xmlRelaxNGFreeInclude:
 * @incl:  a include structure
 *
 * Deallocate a RelaxNG include structure.
 */
static void
xmlRelaxNGFreeInclude(xmlRelaxNGIncludePtr incl)
{
    if (incl == NULL)
        return;

    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 731 732
    xmlFree(incl);
}

733 734 735 736 737 738 739 740 741 742
/**
 * xmlRelaxNGFreeIncludeList:
 * @incl:  a include structure list
 *
 * Deallocate a RelaxNG include structure.
 */
static void
xmlRelaxNGFreeIncludeList(xmlRelaxNGIncludePtr incl)
{
    xmlRelaxNGIncludePtr next;
743

744
    while (incl != NULL) {
745 746 747
        next = incl->next;
        xmlRelaxNGFreeInclude(incl);
        incl = next;
748 749 750
    }
}

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
/**
 * xmlRelaxNGNewRelaxNG:
 * @ctxt:  a Relax-NG validation context (optional)
 *
 * Allocate a new RelaxNG structure.
 *
 * Returns the newly allocated structure or NULL in case or error
 */
static xmlRelaxNGPtr
xmlRelaxNGNewRelaxNG(xmlRelaxNGParserCtxtPtr ctxt)
{
    xmlRelaxNGPtr ret;

    ret = (xmlRelaxNGPtr) xmlMalloc(sizeof(xmlRelaxNG));
    if (ret == NULL) {
766
        xmlRngPErrMemory(ctxt, NULL);
767 768 769 770 771 772 773
        return (NULL);
    }
    memset(ret, 0, sizeof(xmlRelaxNG));

    return (ret);
}

774 775 776 777 778 779 780 781 782 783 784 785 786
/**
 * xmlRelaxNGFreeInnerSchema:
 * @schema:  a schema structure
 *
 * Deallocate a RelaxNG schema structure.
 */
static void
xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema)
{
    if (schema == NULL)
        return;

    if (schema->doc != NULL)
787
        xmlFreeDoc(schema->doc);
788
    if (schema->defTab != NULL) {
789
        int i;
790

791 792 793
        for (i = 0; i < schema->defNr; i++)
            xmlRelaxNGFreeDefine(schema->defTab[i]);
        xmlFree(schema->defTab);
794 795 796 797 798
    }

    xmlFree(schema);
}

799 800 801 802 803 804 805 806 807 808 809 810 811
/**
 * xmlRelaxNGFree:
 * @schema:  a schema structure
 *
 * Deallocate a RelaxNG structure.
 */
void
xmlRelaxNGFree(xmlRelaxNGPtr schema)
{
    if (schema == NULL)
        return;

    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 823 824
        for (i = 0; i < schema->defNr; i++)
            xmlRelaxNGFreeDefine(schema->defTab[i]);
        xmlFree(schema->defTab);
825
    }
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844

    xmlFree(schema);
}

/**
 * xmlRelaxNGNewGrammar:
 * @ctxt:  a Relax-NG validation context (optional)
 *
 * Allocate a new RelaxNG grammar.
 *
 * Returns the newly allocated structure or NULL in case or error
 */
static xmlRelaxNGGrammarPtr
xmlRelaxNGNewGrammar(xmlRelaxNGParserCtxtPtr ctxt)
{
    xmlRelaxNGGrammarPtr ret;

    ret = (xmlRelaxNGGrammarPtr) xmlMalloc(sizeof(xmlRelaxNGGrammar));
    if (ret == NULL) {
845
        xmlRngPErrMemory(ctxt, NULL);
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
        return (NULL);
    }
    memset(ret, 0, sizeof(xmlRelaxNGGrammar));

    return (ret);
}

/**
 * xmlRelaxNGFreeGrammar:
 * @grammar:  a grammar structure
 *
 * Deallocate a RelaxNG grammar structure.
 */
static void
xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar)
{
    if (grammar == NULL)
        return;

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 879 880 881 882 883 884 885 886 887 888 889 890
    }

    xmlFree(grammar);
}

/**
 * xmlRelaxNGNewDefine:
 * @ctxt:  a Relax-NG validation context
 * @node:  the node in the input document.
 *
 * Allocate a new RelaxNG define.
 *
 * Returns the newly allocated structure or NULL in case or error
 */
static xmlRelaxNGDefinePtr
891
xmlRelaxNGNewDefine(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
892 893 894
{
    xmlRelaxNGDefinePtr ret;

895
    if (ctxt->defMax == 0) {
896 897 898 899 900 901 902 903
        ctxt->defMax = 16;
        ctxt->defNr = 0;
        ctxt->defTab = (xmlRelaxNGDefinePtr *)
            xmlMalloc(ctxt->defMax * sizeof(xmlRelaxNGDefinePtr));
        if (ctxt->defTab == NULL) {
            xmlRngPErrMemory(ctxt, "allocating define\n");
            return (NULL);
        }
904
    } else if (ctxt->defMax <= ctxt->defNr) {
905 906 907 908 909 910 911 912 913 914 915 916
        xmlRelaxNGDefinePtr *tmp;

        ctxt->defMax *= 2;
        tmp = (xmlRelaxNGDefinePtr *) xmlRealloc(ctxt->defTab,
                                                 ctxt->defMax *
                                                 sizeof
                                                 (xmlRelaxNGDefinePtr));
        if (tmp == NULL) {
            xmlRngPErrMemory(ctxt, "allocating define\n");
            return (NULL);
        }
        ctxt->defTab = tmp;
917
    }
918 919
    ret = (xmlRelaxNGDefinePtr) xmlMalloc(sizeof(xmlRelaxNGDefine));
    if (ret == NULL) {
920 921
        xmlRngPErrMemory(ctxt, "allocating define\n");
        return (NULL);
922 923
    }
    memset(ret, 0, sizeof(xmlRelaxNGDefine));
924
    ctxt->defTab[ctxt->defNr++] = ret;
925
    ret->node = node;
926
    ret->depth = -1;
927 928 929
    return (ret);
}

930 931 932 933 934 935 936
/**
 * xmlRelaxNGFreePartition:
 * @partitions:  a partition set structure
 *
 * Deallocate RelaxNG partition set structures.
 */
static void
937 938
xmlRelaxNGFreePartition(xmlRelaxNGPartitionPtr partitions)
{
939 940 941 942
    xmlRelaxNGInterleaveGroupPtr group;
    int j;

    if (partitions != NULL) {
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
        if (partitions->groups != NULL) {
            for (j = 0; j < partitions->nbgroups; j++) {
                group = partitions->groups[j];
                if (group != NULL) {
                    if (group->defs != NULL)
                        xmlFree(group->defs);
                    if (group->attrs != NULL)
                        xmlFree(group->attrs);
                    xmlFree(group);
                }
            }
            xmlFree(partitions->groups);
        }
        if (partitions->triage != NULL) {
            xmlHashFree(partitions->triage, NULL);
        }
        xmlFree(partitions);
960 961
    }
}
962

963 964 965 966 967 968 969 970 971 972 973 974
/**
 * xmlRelaxNGFreeDefine:
 * @define:  a define structure
 *
 * Deallocate a RelaxNG define structure.
 */
static void
xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define)
{
    if (define == NULL)
        return;

975 976
    if ((define->type == XML_RELAXNG_VALUE) && (define->attrs != NULL)) {
        xmlRelaxNGTypeLibraryPtr lib;
977

978 979 980
        lib = (xmlRelaxNGTypeLibraryPtr) define->data;
        if ((lib != NULL) && (lib->freef != NULL))
            lib->freef(lib->data, (void *) define->attrs);
981
    }
982 983 984 985
    if ((define->data != NULL) && (define->type == XML_RELAXNG_INTERLEAVE))
        xmlRelaxNGFreePartition((xmlRelaxNGPartitionPtr) define->data);
    if ((define->data != NULL) && (define->type == XML_RELAXNG_CHOICE))
        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 993
    if (define->contModel != NULL)
        xmlRegFreeRegexp(define->contModel);
994 995 996
    xmlFree(define);
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
/**
 * xmlRelaxNGNewStates:
 * @ctxt:  a Relax-NG validation context
 * @size:  the default size for the container
 *
 * Allocate a new RelaxNG validation state container
 *
 * Returns the newly allocated structure or NULL in case or error
 */
static xmlRelaxNGStatesPtr
xmlRelaxNGNewStates(xmlRelaxNGValidCtxtPtr ctxt, int size)
{
    xmlRelaxNGStatesPtr ret;

1011
    if ((ctxt != NULL) &&
1012
        (ctxt->freeStates != NULL) && (ctxt->freeStatesNr > 0)) {
1013 1014 1015 1016
        ctxt->freeStatesNr--;
        ret = ctxt->freeStates[ctxt->freeStatesNr];
        ret->nbState = 0;
        return (ret);
1017
    }
1018 1019
    if (size < 16)
        size = 16;
1020 1021

    ret = (xmlRelaxNGStatesPtr) xmlMalloc(sizeof(xmlRelaxNGStates) +
1022 1023 1024
                                          (size -
                                           1) *
                                          sizeof(xmlRelaxNGValidStatePtr));
1025
    if (ret == NULL) {
1026
        xmlRngVErrMemory(ctxt, "allocating states\n");
1027 1028 1029 1030
        return (NULL);
    }
    ret->nbState = 0;
    ret->maxState = size;
1031 1032 1033
    ret->tabState = (xmlRelaxNGValidStatePtr *) xmlMalloc((size) *
                                                          sizeof
                                                          (xmlRelaxNGValidStatePtr));
1034
    if (ret->tabState == NULL) {
1035 1036
        xmlRngVErrMemory(ctxt, "allocating states\n");
        xmlFree(ret);
1037 1038
        return (NULL);
    }
1039
    return (ret);
1040 1041
}

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
/**
 * xmlRelaxNGAddStateUniq:
 * @ctxt:  a Relax-NG validation context
 * @states:  the states container
 * @state:  the validation state
 *
 * Add a RelaxNG validation state to the container without checking
 * for unicity.
 *
 * Return 1 in case of success and 0 if this is a duplicate and -1 on error
 */
static int
xmlRelaxNGAddStatesUniq(xmlRelaxNGValidCtxtPtr ctxt,
1055 1056
                        xmlRelaxNGStatesPtr states,
                        xmlRelaxNGValidStatePtr state)
1057 1058
{
    if (state == NULL) {
1059
        return (-1);
1060 1061
    }
    if (states->nbState >= states->maxState) {
1062 1063 1064 1065 1066 1067 1068 1069
        xmlRelaxNGValidStatePtr *tmp;
        int size;

        size = states->maxState * 2;
        tmp = (xmlRelaxNGValidStatePtr *) xmlRealloc(states->tabState,
                                                     (size) *
                                                     sizeof
                                                     (xmlRelaxNGValidStatePtr));
1070
        if (tmp == NULL) {
1071 1072 1073 1074 1075
            xmlRngVErrMemory(ctxt, "adding states\n");
            return (-1);
        }
        states->tabState = tmp;
        states->maxState = size;
1076 1077
    }
    states->tabState[states->nbState++] = state;
1078
    return (1);
1079 1080
}

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
/**
 * xmlRelaxNGAddState:
 * @ctxt:  a Relax-NG validation context
 * @states:  the states container
 * @state:  the validation state
 *
 * Add a RelaxNG validation state to the container
 *
 * Return 1 in case of success and 0 if this is a duplicate and -1 on error
 */
static int
1092 1093 1094
xmlRelaxNGAddStates(xmlRelaxNGValidCtxtPtr ctxt,
                    xmlRelaxNGStatesPtr states,
                    xmlRelaxNGValidStatePtr state)
1095 1096 1097
{
    int i;

Gaurav's avatar
Gaurav committed
1098
    if (state == NULL || states == NULL) {
1099
        return (-1);
1100 1101
    }
    if (states->nbState >= states->maxState) {
1102 1103 1104 1105 1106 1107 1108 1109
        xmlRelaxNGValidStatePtr *tmp;
        int size;

        size = states->maxState * 2;
        tmp = (xmlRelaxNGValidStatePtr *) xmlRealloc(states->tabState,
                                                     (size) *
                                                     sizeof
                                                     (xmlRelaxNGValidStatePtr));
1110
        if (tmp == NULL) {
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
            xmlRngVErrMemory(ctxt, "adding states\n");
            return (-1);
        }
        states->tabState = tmp;
        states->maxState = size;
    }
    for (i = 0; i < states->nbState; i++) {
        if (xmlRelaxNGEqualValidState(ctxt, state, states->tabState[i])) {
            xmlRelaxNGFreeValidState(ctxt, state);
            return (0);
        }
1122 1123
    }
    states->tabState[states->nbState++] = state;
1124
    return (1);
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
}

/**
 * xmlRelaxNGFreeStates:
 * @ctxt:  a Relax-NG validation context
 * @states:  teh container
 *
 * Free a RelaxNG validation state container
 */
static void
1135
xmlRelaxNGFreeStates(xmlRelaxNGValidCtxtPtr ctxt,
1136
                     xmlRelaxNGStatesPtr states)
1137
{
1138
    if (states == NULL)
1139
        return;
1140
    if ((ctxt != NULL) && (ctxt->freeStates == NULL)) {
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        ctxt->freeStatesMax = 40;
        ctxt->freeStatesNr = 0;
        ctxt->freeStates = (xmlRelaxNGStatesPtr *)
            xmlMalloc(ctxt->freeStatesMax * sizeof(xmlRelaxNGStatesPtr));
        if (ctxt->freeStates == NULL) {
            xmlRngVErrMemory(ctxt, "storing states\n");
        }
    } else if ((ctxt != NULL)
               && (ctxt->freeStatesNr >= ctxt->freeStatesMax)) {
        xmlRelaxNGStatesPtr *tmp;

        tmp = (xmlRelaxNGStatesPtr *) xmlRealloc(ctxt->freeStates,
                                                 2 * ctxt->freeStatesMax *
                                                 sizeof
                                                 (xmlRelaxNGStatesPtr));
        if (tmp == NULL) {
            xmlRngVErrMemory(ctxt, "storing states\n");
            xmlFree(states->tabState);
            xmlFree(states);
            return;
        }
        ctxt->freeStates = tmp;
        ctxt->freeStatesMax *= 2;
1164
    }
1165
    if ((ctxt == NULL) || (ctxt->freeStates == NULL)) {
1166 1167
        xmlFree(states->tabState);
        xmlFree(states);
1168
    } else {
1169
        ctxt->freeStates[ctxt->freeStatesNr++] = states;
1170 1171 1172
    }
}

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
/**
 * xmlRelaxNGNewValidState:
 * @ctxt:  a Relax-NG validation context
 * @node:  the current node or NULL for the document
 *
 * Allocate a new RelaxNG validation state
 *
 * Returns the newly allocated structure or NULL in case or error
 */
static xmlRelaxNGValidStatePtr
xmlRelaxNGNewValidState(xmlRelaxNGValidCtxtPtr ctxt, xmlNodePtr node)
{
    xmlRelaxNGValidStatePtr ret;
    xmlAttrPtr attr;
    xmlAttrPtr attrs[MAX_ATTR];
    int nbAttrs = 0;
    xmlNodePtr root = NULL;

    if (node == NULL) {
1192 1193 1194
        root = xmlDocGetRootElement(ctxt->doc);
        if (root == NULL)
            return (NULL);
1195
    } else {
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        attr = node->properties;
        while (attr != NULL) {
            if (nbAttrs < MAX_ATTR)
                attrs[nbAttrs++] = attr;
            else
                nbAttrs++;
            attr = attr->next;
        }
    }
    if ((ctxt->freeState != NULL) && (ctxt->freeState->nbState > 0)) {
        ctxt->freeState->nbState--;
        ret = ctxt->freeState->tabState[ctxt->freeState->nbState];
1208
    } else {
1209 1210 1211 1212 1213 1214 1215 1216
        ret =
            (xmlRelaxNGValidStatePtr)
            xmlMalloc(sizeof(xmlRelaxNGValidState));
        if (ret == NULL) {
            xmlRngVErrMemory(ctxt, "allocating states\n");
            return (NULL);
        }
        memset(ret, 0, sizeof(xmlRelaxNGValidState));
1217
    }
1218 1219
    ret->value = NULL;
    ret->endvalue = NULL;
1220
    if (node == NULL) {
1221 1222
        ret->node = (xmlNodePtr) ctxt->doc;
        ret->seq = root;
1223
    } else {
1224 1225
        ret->node = node;
        ret->seq = node->children;
1226 1227 1228
    }
    ret->nbAttrs = 0;
    if (nbAttrs > 0) {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        if (ret->attrs == NULL) {
            if (nbAttrs < 4)
                ret->maxAttrs = 4;
            else
                ret->maxAttrs = nbAttrs;
            ret->attrs = (xmlAttrPtr *) xmlMalloc(ret->maxAttrs *
                                                  sizeof(xmlAttrPtr));
            if (ret->attrs == NULL) {
                xmlRngVErrMemory(ctxt, "allocating states\n");
                return (ret);
            }
        } else if (ret->maxAttrs < nbAttrs) {
            xmlAttrPtr *tmp;

            tmp = (xmlAttrPtr *) xmlRealloc(ret->attrs, nbAttrs *
                                            sizeof(xmlAttrPtr));
            if (tmp == NULL) {
                xmlRngVErrMemory(ctxt, "allocating states\n");
                return (ret);
            }
            ret->attrs = tmp;
            ret->maxAttrs = nbAttrs;
        }
        ret->nbAttrs = nbAttrs;
        if (nbAttrs < MAX_ATTR) {
            memcpy(ret->attrs, attrs, sizeof(xmlAttrPtr) * nbAttrs);
        } else {
            attr = node->properties;
            nbAttrs = 0;
            while (attr != NULL) {
                ret->attrs[nbAttrs++] = attr;
                attr = attr->next;
            }
        }
1263
    }
1264
    ret->nbAttrLeft = ret->nbAttrs;
1265 1266 1267
    return (ret);
}

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
/**
 * xmlRelaxNGCopyValidState:
 * @ctxt:  a Relax-NG validation context
 * @state:  a validation state
 *
 * Copy the validation state
 *
 * Returns the newly allocated structure or NULL in case or error
 */
static xmlRelaxNGValidStatePtr
xmlRelaxNGCopyValidState(xmlRelaxNGValidCtxtPtr ctxt,
1279
                         xmlRelaxNGValidStatePtr state)
1280 1281
{
    xmlRelaxNGValidStatePtr ret;
1282 1283
    unsigned int maxAttrs;
    xmlAttrPtr *attrs;
1284 1285

    if (state == NULL)
1286 1287 1288 1289
        return (NULL);
    if ((ctxt->freeState != NULL) && (ctxt->freeState->nbState > 0)) {
        ctxt->freeState->nbState--;
        ret = ctxt->freeState->tabState[ctxt->freeState->nbState];
1290
    } else {
1291 1292 1293 1294 1295 1296 1297 1298
        ret =
            (xmlRelaxNGValidStatePtr)
            xmlMalloc(sizeof(xmlRelaxNGValidState));
        if (ret == NULL) {
            xmlRngVErrMemory(ctxt, "allocating states\n");
            return (NULL);
        }
        memset(ret, 0, sizeof(xmlRelaxNGValidState));
1299 1300 1301 1302 1303 1304 1305
    }
    attrs = ret->attrs;
    maxAttrs = ret->maxAttrs;
    memcpy(ret, state, sizeof(xmlRelaxNGValidState));
    ret->attrs = attrs;
    ret->maxAttrs = maxAttrs;
    if (state->nbAttrs > 0) {
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
        if (ret->attrs == NULL) {
            ret->maxAttrs = state->maxAttrs;
            ret->attrs = (xmlAttrPtr *) xmlMalloc(ret->maxAttrs *
                                                  sizeof(xmlAttrPtr));
            if (ret->attrs == NULL) {
                xmlRngVErrMemory(ctxt, "allocating states\n");
                ret->nbAttrs = 0;
                return (ret);
            }
        } else if (ret->maxAttrs < state->nbAttrs) {
            xmlAttrPtr *tmp;

            tmp = (xmlAttrPtr *) xmlRealloc(ret->attrs, state->maxAttrs *
                                            sizeof(xmlAttrPtr));
            if (tmp == NULL) {
                xmlRngVErrMemory(ctxt, "allocating states\n");
                ret->nbAttrs = 0;
                return (ret);
            }
            ret->maxAttrs = state->maxAttrs;
            ret->attrs = tmp;
        }
        memcpy(ret->attrs, state->attrs,
               state->nbAttrs * sizeof(xmlAttrPtr));
    }
    return (ret);
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
}

/**
 * xmlRelaxNGEqualValidState:
 * @ctxt:  a Relax-NG validation context
 * @state1:  a validation state
 * @state2:  a validation state
 *
 * Compare the validation states for equality
 *
 * Returns 1 if equald, 0 otherwise
 */
static int
xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
1346 1347
                          xmlRelaxNGValidStatePtr state1,
                          xmlRelaxNGValidStatePtr state2)
1348 1349 1350 1351
{
    int i;

    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 1367 1368 1369 1370
        (!xmlStrEqual(state1->value, state2->value)))
        return (0);
    for (i = 0; i < state1->nbAttrs; i++) {
        if (state1->attrs[i] != state2->attrs[i])
            return (0);
1371
    }
1372
    return (1);
1373 1374
}

1375 1376 1377 1378 1379 1380 1381
/**
 * xmlRelaxNGFreeValidState:
 * @state:  a validation state structure
 *
 * Deallocate a RelaxNG validation state structure.
 */
static void
1382
xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,
1383
                         xmlRelaxNGValidStatePtr state)
1384 1385 1386 1387
{
    if (state == NULL)
        return;

1388
    if ((ctxt != NULL) && (ctxt->freeState == NULL)) {
1389
        ctxt->freeState = xmlRelaxNGNewStates(ctxt, 40);
1390 1391
    }
    if ((ctxt == NULL) || (ctxt->freeState == NULL)) {
1392 1393 1394
        if (state->attrs != NULL)
            xmlFree(state->attrs);
        xmlFree(state);
1395
    } else {
1396
        xmlRelaxNGAddStatesUniq(ctxt, ctxt->freeState, state);
1397
    }
1398 1399
}

1400
/************************************************************************
1401 1402 1403
 *									*
 *			Semi internal functions				*
 *									*
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
 ************************************************************************/

/**
 * xmlRelaxParserSetFlag:
 * @ctxt: a RelaxNG parser context
 * @flags: a set of flags values
 *
 * Semi private function used to pass informations to a parser context
 * which are a combination of xmlRelaxNGParserFlag .
 *
 * Returns 0 if success and -1 in case of error
 */
int
xmlRelaxParserSetFlag(xmlRelaxNGParserCtxtPtr ctxt, int flags)
{
    if (ctxt == NULL) return(-1);
    if (flags & XML_RELAXNGP_FREE_DOC) {
        ctxt->crng |= XML_RELAXNGP_FREE_DOC;
	flags -= XML_RELAXNGP_FREE_DOC;
    }
    if (flags & XML_RELAXNGP_CRNG) {
        ctxt->crng |= XML_RELAXNGP_CRNG;
	flags -= XML_RELAXNGP_CRNG;
    }
    if (flags != 0) return(-1);
    return(0);
}

/************************************************************************
1433 1434 1435
 *									*
 *			Document functions				*
 *									*
1436 1437
 ************************************************************************/
static xmlDocPtr xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt,
1438
                                      xmlDocPtr doc);
1439

1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
/**
 * xmlRelaxNGIncludePush:
 * @ctxt:  the parser context
 * @value:  the element doc
 *
 * Pushes a new include on top of the include stack
 *
 * Returns 0 in case of error, the index in the stack otherwise
 */
static int
xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,
1451
                      xmlRelaxNGIncludePtr value)
1452 1453
{
    if (ctxt->incTab == NULL) {
1454 1455 1456 1457 1458
        ctxt->incMax = 4;
        ctxt->incNr = 0;
        ctxt->incTab =
            (xmlRelaxNGIncludePtr *) xmlMalloc(ctxt->incMax *
                                               sizeof(ctxt->incTab[0]));
1459
        if (ctxt->incTab == NULL) {
1460
            xmlRngPErrMemory(ctxt, "allocating include\n");
1461 1462 1463 1464 1465 1466 1467
            return (0);
        }
    }
    if (ctxt->incNr >= ctxt->incMax) {
        ctxt->incMax *= 2;
        ctxt->incTab =
            (xmlRelaxNGIncludePtr *) xmlRealloc(ctxt->incTab,
1468 1469
                                                ctxt->incMax *
                                                sizeof(ctxt->incTab[0]));
1470
        if (ctxt->incTab == NULL) {
1471
            xmlRngPErrMemory(ctxt, "allocating include\n");
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
            return (0);
        }
    }
    ctxt->incTab[ctxt->incNr] = value;
    ctxt->inc = value;
    return (ctxt->incNr++);
}

/**
 * xmlRelaxNGIncludePop:
 * @ctxt: the parser context
 *
 * Pops the top include from the include stack
 *
 * Returns the include just removed
 */
static xmlRelaxNGIncludePtr
xmlRelaxNGIncludePop(xmlRelaxNGParserCtxtPtr ctxt)
{
    xmlRelaxNGIncludePtr ret;

    if (ctxt->incNr <= 0)
1494
        return (NULL);
1495 1496 1497 1498 1499 1500
    ctxt->incNr--;
    if (ctxt->incNr > 0)
        ctxt->inc = ctxt->incTab[ctxt->incNr - 1];
    else
        ctxt->inc = NULL;
    ret = ctxt->incTab[ctxt->incNr];
1501
    ctxt->incTab[ctxt->incNr] = NULL;
1502 1503 1504
    return (ret);
}

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
/**
 * xmlRelaxNGRemoveRedefine:
 * @ctxt: the parser context
 * @URL:  the normalized URL
 * @target:  the included target
 * @name:  the define name to eliminate
 *
 * Applies the elimination algorithm of 4.7
 *
 * Returns 0 in case of error, 1 in case of success.
 */
static int
xmlRelaxNGRemoveRedefine(xmlRelaxNGParserCtxtPtr ctxt,
1518 1519 1520
                         const xmlChar * URL ATTRIBUTE_UNUSED,
                         xmlNodePtr target, const xmlChar * name)
{
1521 1522 1523 1524 1525
    int found = 0;
    xmlNodePtr tmp, tmp2;
    xmlChar *name2;

#ifdef DEBUG_INCLUDE
1526
    if (name == NULL)
1527 1528
        xmlGenericError(xmlGenericErrorContext,
                        "Elimination of <include> start from %s\n", URL);
1529
    else
1530 1531 1532
        xmlGenericError(xmlGenericErrorContext,
                        "Elimination of <include> define %s from %s\n",
                        name, URL);
1533 1534 1535
#endif
    tmp = target;
    while (tmp != NULL) {
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
        tmp2 = tmp->next;
        if ((name == NULL) && (IS_RELAXNG(tmp, "start"))) {
            found = 1;
            xmlUnlinkNode(tmp);
            xmlFreeNode(tmp);
        } else if ((name != NULL) && (IS_RELAXNG(tmp, "define"))) {
            name2 = xmlGetProp(tmp, BAD_CAST "name");
            xmlRelaxNGNormExtSpace(name2);
            if (name2 != NULL) {
                if (xmlStrEqual(name, name2)) {
                    found = 1;
                    xmlUnlinkNode(tmp);
                    xmlFreeNode(tmp);
                }
                xmlFree(name2);
            }
        } else if (IS_RELAXNG(tmp, "include")) {
            xmlChar *href = NULL;
1554
            xmlRelaxNGDocumentPtr inc = tmp->psvi;
1555 1556 1557 1558 1559 1560

            if ((inc != NULL) && (inc->doc != NULL) &&
                (inc->doc->children != NULL)) {

                if (xmlStrEqual
                    (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 1566
                                                 xmlDocGetRootElement(inc->doc)->children,
                                                 name) == 1) {