2 * regexp.c: generic and extensible Regular Expression engine
4 * Basically designed with the purpose of compiling regexps for
5 * the variety of validation/shemas mechanisms now available in
6 * XML related specifications these include:
7 * - XML-1.0 DTD validation
8 * - XML Schemas structure part 1
9 * - XML Schemas Datatypes part 2 especially Appendix F
10 * - RELAX-NG/TREX i.e. the counter proposal
12 * See Copyright for the status of this software.
14 * Daniel Veillard <veillard@redhat.com>
20 #ifdef LIBXML_REGEXP_ENABLED
22 /* #define DEBUG_ERR */
30 #include <libxml/tree.h>
31 #include <libxml/parserInternals.h>
32 #include <libxml/xmlregexp.h>
33 #include <libxml/xmlautomata.h>
34 #include <libxml/xmlunicode.h>
37 #define INT_MAX 123456789 /* easy to flag and big enough for our needs */
40 /* #define DEBUG_REGEXP_GRAPH */
41 /* #define DEBUG_REGEXP_EXEC */
42 /* #define DEBUG_PUSH */
43 /* #define DEBUG_COMPACTION */
45 #define MAX_PUSH 10000000
48 ctxt->error = XML_REGEXP_COMPILE_ERROR; \
49 xmlRegexpErrCompile(ctxt, str);
50 #define NEXT ctxt->cur++
51 #define CUR (*(ctxt->cur))
52 #define NXT(index) (ctxt->cur[index])
54 #define CUR_SCHAR(s, l) xmlStringCurrentChar(NULL, s, &l)
55 #define NEXTL(l) ctxt->cur += l;
56 #define XML_REG_STRING_SEPARATOR '|'
61 * macro to flag unimplemented blocks
64 xmlGenericError(xmlGenericErrorContext, \
65 "Unimplemented block at %s:%d\n", \
68 /************************************************************************
70 * Datatypes and structures *
72 ************************************************************************/
75 * Note: the order of the enums below is significant, do not shuffle
78 XML_REGEXP_EPSILON = 1,
81 XML_REGEXP_SUBREG, /* used for () sub regexps */
83 XML_REGEXP_ANYCHAR, /* . */
84 XML_REGEXP_ANYSPACE, /* \s */
85 XML_REGEXP_NOTSPACE, /* \S */
86 XML_REGEXP_INITNAME, /* \l */
87 XML_REGEXP_NOTINITNAME, /* \L */
88 XML_REGEXP_NAMECHAR, /* \c */
89 XML_REGEXP_NOTNAMECHAR, /* \C */
90 XML_REGEXP_DECIMAL, /* \d */
91 XML_REGEXP_NOTDECIMAL, /* \D */
92 XML_REGEXP_REALCHAR, /* \w */
93 XML_REGEXP_NOTREALCHAR, /* \W */
94 XML_REGEXP_LETTER = 100,
95 XML_REGEXP_LETTER_UPPERCASE,
96 XML_REGEXP_LETTER_LOWERCASE,
97 XML_REGEXP_LETTER_TITLECASE,
98 XML_REGEXP_LETTER_MODIFIER,
99 XML_REGEXP_LETTER_OTHERS,
101 XML_REGEXP_MARK_NONSPACING,
102 XML_REGEXP_MARK_SPACECOMBINING,
103 XML_REGEXP_MARK_ENCLOSING,
105 XML_REGEXP_NUMBER_DECIMAL,
106 XML_REGEXP_NUMBER_LETTER,
107 XML_REGEXP_NUMBER_OTHERS,
109 XML_REGEXP_PUNCT_CONNECTOR,
110 XML_REGEXP_PUNCT_DASH,
111 XML_REGEXP_PUNCT_OPEN,
112 XML_REGEXP_PUNCT_CLOSE,
113 XML_REGEXP_PUNCT_INITQUOTE,
114 XML_REGEXP_PUNCT_FINQUOTE,
115 XML_REGEXP_PUNCT_OTHERS,
117 XML_REGEXP_SEPAR_SPACE,
118 XML_REGEXP_SEPAR_LINE,
119 XML_REGEXP_SEPAR_PARA,
121 XML_REGEXP_SYMBOL_MATH,
122 XML_REGEXP_SYMBOL_CURRENCY,
123 XML_REGEXP_SYMBOL_MODIFIER,
124 XML_REGEXP_SYMBOL_OTHERS,
126 XML_REGEXP_OTHER_CONTROL,
127 XML_REGEXP_OTHER_FORMAT,
128 XML_REGEXP_OTHER_PRIVATE,
130 XML_REGEXP_BLOCK_NAME
134 XML_REGEXP_QUANT_EPSILON = 1,
135 XML_REGEXP_QUANT_ONCE,
136 XML_REGEXP_QUANT_OPT,
137 XML_REGEXP_QUANT_MULT,
138 XML_REGEXP_QUANT_PLUS,
139 XML_REGEXP_QUANT_ONCEONLY,
140 XML_REGEXP_QUANT_ALL,
141 XML_REGEXP_QUANT_RANGE
145 XML_REGEXP_START_STATE = 1,
146 XML_REGEXP_FINAL_STATE,
147 XML_REGEXP_TRANS_STATE,
148 XML_REGEXP_SINK_STATE
152 XML_REGEXP_MARK_NORMAL = 0,
153 XML_REGEXP_MARK_START,
154 XML_REGEXP_MARK_VISITED
157 typedef struct _xmlRegRange xmlRegRange;
158 typedef xmlRegRange *xmlRegRangePtr;
160 struct _xmlRegRange {
161 int neg; /* 0 normal, 1 not, 2 exclude */
168 typedef struct _xmlRegAtom xmlRegAtom;
169 typedef xmlRegAtom *xmlRegAtomPtr;
171 typedef struct _xmlAutomataState xmlRegState;
172 typedef xmlRegState *xmlRegStatePtr;
177 xmlRegQuantType quant;
185 xmlRegStatePtr start;
189 xmlRegRangePtr *ranges;
193 typedef struct _xmlRegCounter xmlRegCounter;
194 typedef xmlRegCounter *xmlRegCounterPtr;
196 struct _xmlRegCounter {
201 typedef struct _xmlRegTrans xmlRegTrans;
202 typedef xmlRegTrans *xmlRegTransPtr;
204 struct _xmlRegTrans {
212 struct _xmlAutomataState {
213 xmlRegStateType type;
214 xmlRegMarkedType mark;
215 xmlRegMarkedType reached;
220 /* knowing states ponting to us can speed things up */
226 typedef struct _xmlAutomata xmlRegParserCtxt;
227 typedef xmlRegParserCtxt *xmlRegParserCtxtPtr;
229 struct _xmlAutomata {
236 xmlRegStatePtr start;
238 xmlRegStatePtr state;
244 xmlRegAtomPtr *atoms;
248 xmlRegStatePtr *states;
252 xmlRegCounter *counters;
261 xmlRegStatePtr *states;
263 xmlRegAtomPtr *atoms;
265 xmlRegCounter *counters;
268 * That's the compact form for determinists automatas
277 typedef struct _xmlRegExecRollback xmlRegExecRollback;
278 typedef xmlRegExecRollback *xmlRegExecRollbackPtr;
280 struct _xmlRegExecRollback {
281 xmlRegStatePtr state;/* the current state */
282 int index; /* the index in the input stack */
283 int nextbranch; /* the next transition to explore in that state */
284 int *counts; /* save the automata state if it has some */
287 typedef struct _xmlRegInputToken xmlRegInputToken;
288 typedef xmlRegInputToken *xmlRegInputTokenPtr;
290 struct _xmlRegInputToken {
295 struct _xmlRegExecCtxt {
296 int status; /* execution status != 0 indicate an error */
297 int determinist; /* did we find an indeterministic behaviour */
298 xmlRegexpPtr comp; /* the compiled regexp */
299 xmlRegExecCallbacks callback;
302 xmlRegStatePtr state;/* the current state */
303 int transno; /* the current transition on that state */
304 int transcount; /* the number of chars in char counted transitions */
307 * A stack of rollback states
311 xmlRegExecRollback *rollbacks;
314 * The state of the automata if any
325 const xmlChar *inputString; /* when operating on characters */
326 xmlRegInputTokenPtr inputStack;/* when operating on strings */
331 int errStateNo; /* the error state number */
332 xmlRegStatePtr errState; /* the error state */
333 xmlChar *errString; /* the string raising the error */
334 int *errCounts; /* counters at the error state */
338 #define REGEXP_ALL_COUNTER 0x123456
339 #define REGEXP_ALL_LAX_COUNTER 0x123457
341 static void xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top);
342 static void xmlRegFreeState(xmlRegStatePtr state);
343 static void xmlRegFreeAtom(xmlRegAtomPtr atom);
344 static int xmlRegStrEqualWildcard(const xmlChar *expStr, const xmlChar *valStr);
345 static int xmlRegCheckCharacter(xmlRegAtomPtr atom, int codepoint);
346 static int xmlRegCheckCharacterRange(xmlRegAtomType type, int codepoint,
347 int neg, int start, int end, const xmlChar *blockName);
349 /************************************************************************
351 * Regexp memory error handler *
353 ************************************************************************/
355 * xmlRegexpErrMemory:
356 * @extra: extra information
358 * Handle an out of memory condition
361 xmlRegexpErrMemory(xmlRegParserCtxtPtr ctxt, const char *extra)
363 const char *regexp = NULL;
365 regexp = (const char *) ctxt->string;
366 ctxt->error = XML_ERR_NO_MEMORY;
368 __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_REGEXP,
369 XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
371 "Memory allocation failed : %s\n", extra);
375 * xmlRegexpErrCompile:
376 * @extra: extra information
378 * Handle a compilation failure
381 xmlRegexpErrCompile(xmlRegParserCtxtPtr ctxt, const char *extra)
383 const char *regexp = NULL;
387 regexp = (const char *) ctxt->string;
388 idx = ctxt->cur - ctxt->string;
389 ctxt->error = XML_REGEXP_COMPILE_ERROR;
391 __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_REGEXP,
392 XML_REGEXP_COMPILE_ERROR, XML_ERR_FATAL, NULL, 0, extra,
393 regexp, NULL, idx, 0,
394 "failed to compile: %s\n", extra);
397 /************************************************************************
399 * Allocation/Deallocation *
401 ************************************************************************/
403 static int xmlFAComputesDeterminism(xmlRegParserCtxtPtr ctxt);
405 * xmlRegEpxFromParse:
406 * @ctxt: the parser context used to build it
408 * Allocate a new regexp and fill it with the result from the parser
410 * Returns the new regexp or NULL in case of error
413 xmlRegEpxFromParse(xmlRegParserCtxtPtr ctxt) {
416 ret = (xmlRegexpPtr) xmlMalloc(sizeof(xmlRegexp));
418 xmlRegexpErrMemory(ctxt, "compiling regexp");
421 memset(ret, 0, sizeof(xmlRegexp));
422 ret->string = ctxt->string;
423 ret->nbStates = ctxt->nbStates;
424 ret->states = ctxt->states;
425 ret->nbAtoms = ctxt->nbAtoms;
426 ret->atoms = ctxt->atoms;
427 ret->nbCounters = ctxt->nbCounters;
428 ret->counters = ctxt->counters;
429 ret->determinist = ctxt->determinist;
430 if (ret->determinist == -1) {
431 xmlRegexpIsDeterminist(ret);
434 if ((ret->determinist != 0) &&
435 (ret->nbCounters == 0) &&
437 (ret->atoms != NULL) &&
438 (ret->atoms[0] != NULL) &&
439 (ret->atoms[0]->type == XML_REGEXP_STRING)) {
440 int i, j, nbstates = 0, nbatoms = 0;
449 * Switch to a compact representation
450 * 1/ counting the effective number of states left
451 * 2/ counting the unique number of atoms, and check that
452 * they are all of the string type
453 * 3/ build a table state x atom for the transitions
456 stateRemap = xmlMalloc(ret->nbStates * sizeof(int));
457 if (stateRemap == NULL) {
458 xmlRegexpErrMemory(ctxt, "compiling regexp");
462 for (i = 0;i < ret->nbStates;i++) {
463 if (ret->states[i] != NULL) {
464 stateRemap[i] = nbstates;
470 #ifdef DEBUG_COMPACTION
471 printf("Final: %d states\n", nbstates);
473 stringMap = xmlMalloc(ret->nbAtoms * sizeof(char *));
474 if (stringMap == NULL) {
475 xmlRegexpErrMemory(ctxt, "compiling regexp");
480 stringRemap = xmlMalloc(ret->nbAtoms * sizeof(int));
481 if (stringRemap == NULL) {
482 xmlRegexpErrMemory(ctxt, "compiling regexp");
488 for (i = 0;i < ret->nbAtoms;i++) {
489 if ((ret->atoms[i]->type == XML_REGEXP_STRING) &&
490 (ret->atoms[i]->quant == XML_REGEXP_QUANT_ONCE)) {
491 value = ret->atoms[i]->valuep;
492 for (j = 0;j < nbatoms;j++) {
493 if (xmlStrEqual(stringMap[j], value)) {
499 stringRemap[i] = nbatoms;
500 stringMap[nbatoms] = xmlStrdup(value);
501 if (stringMap[nbatoms] == NULL) {
502 for (i = 0;i < nbatoms;i++)
503 xmlFree(stringMap[i]);
504 xmlFree(stringRemap);
514 xmlFree(stringRemap);
515 for (i = 0;i < nbatoms;i++)
516 xmlFree(stringMap[i]);
522 #ifdef DEBUG_COMPACTION
523 printf("Final: %d atoms\n", nbatoms);
525 transitions = (int *) xmlMalloc((nbstates + 1) *
526 (nbatoms + 1) * sizeof(int));
527 if (transitions == NULL) {
529 xmlFree(stringRemap);
534 memset(transitions, 0, (nbstates + 1) * (nbatoms + 1) * sizeof(int));
537 * Allocate the transition table. The first entry for each
538 * state corresponds to the state type.
542 for (i = 0;i < ret->nbStates;i++) {
543 int stateno, atomno, targetno, prev;
544 xmlRegStatePtr state;
545 xmlRegTransPtr trans;
547 stateno = stateRemap[i];
550 state = ret->states[i];
552 transitions[stateno * (nbatoms + 1)] = state->type;
554 for (j = 0;j < state->nbTrans;j++) {
555 trans = &(state->trans[j]);
556 if ((trans->to == -1) || (trans->atom == NULL))
558 atomno = stringRemap[trans->atom->no];
559 if ((trans->atom->data != NULL) && (transdata == NULL)) {
560 transdata = (void **) xmlMalloc(nbstates * nbatoms *
562 if (transdata != NULL)
564 nbstates * nbatoms * sizeof(void *));
566 xmlRegexpErrMemory(ctxt, "compiling regexp");
570 targetno = stateRemap[trans->to];
572 * if the same atom can generate transitions to 2 different
573 * states then it means the automata is not determinist and
574 * the compact form can't be used !
576 prev = transitions[stateno * (nbatoms + 1) + atomno + 1];
578 if (prev != targetno + 1) {
579 ret->determinist = 0;
580 #ifdef DEBUG_COMPACTION
581 printf("Indet: state %d trans %d, atom %d to %d : %d to %d\n",
582 i, j, trans->atom->no, trans->to, atomno, targetno);
583 printf(" previous to is %d\n", prev);
585 if (transdata != NULL)
587 xmlFree(transitions);
589 xmlFree(stringRemap);
590 for (i = 0;i < nbatoms;i++)
591 xmlFree(stringMap[i]);
597 printf("State %d trans %d: atom %d to %d : %d to %d\n",
598 i, j, trans->atom->no, trans->to, atomno, targetno);
600 transitions[stateno * (nbatoms + 1) + atomno + 1] =
601 targetno + 1; /* to avoid 0 */
602 if (transdata != NULL)
603 transdata[stateno * nbatoms + atomno] =
608 ret->determinist = 1;
609 #ifdef DEBUG_COMPACTION
613 for (i = 0;i < nbstates;i++) {
614 for (j = 0;j < nbatoms + 1;j++) {
615 printf("%02d ", transitions[i * (nbatoms + 1) + j]);
622 * Cleanup of the old data
624 if (ret->states != NULL) {
625 for (i = 0;i < ret->nbStates;i++)
626 xmlRegFreeState(ret->states[i]);
627 xmlFree(ret->states);
631 if (ret->atoms != NULL) {
632 for (i = 0;i < ret->nbAtoms;i++)
633 xmlRegFreeAtom(ret->atoms[i]);
639 ret->compact = transitions;
640 ret->transdata = transdata;
641 ret->stringMap = stringMap;
642 ret->nbstrings = nbatoms;
643 ret->nbstates = nbstates;
645 xmlFree(stringRemap);
653 ctxt->nbCounters = 0;
654 ctxt->counters = NULL;
659 * xmlRegNewParserCtxt:
660 * @string: the string to parse
662 * Allocate a new regexp parser context
664 * Returns the new context or NULL in case of error
666 static xmlRegParserCtxtPtr
667 xmlRegNewParserCtxt(const xmlChar *string) {
668 xmlRegParserCtxtPtr ret;
670 ret = (xmlRegParserCtxtPtr) xmlMalloc(sizeof(xmlRegParserCtxt));
673 memset(ret, 0, sizeof(xmlRegParserCtxt));
675 ret->string = xmlStrdup(string);
676 ret->cur = ret->string;
680 ret->determinist = -1;
686 * @ctxt: the regexp parser context
687 * @neg: is that negative
688 * @type: the type of range
689 * @start: the start codepoint
690 * @end: the end codepoint
692 * Allocate a new regexp range
694 * Returns the new range or NULL in case of error
696 static xmlRegRangePtr
697 xmlRegNewRange(xmlRegParserCtxtPtr ctxt,
698 int neg, xmlRegAtomType type, int start, int end) {
701 ret = (xmlRegRangePtr) xmlMalloc(sizeof(xmlRegRange));
703 xmlRegexpErrMemory(ctxt, "allocating range");
715 * @range: the regexp range
717 * Free a regexp range
720 xmlRegFreeRange(xmlRegRangePtr range) {
724 if (range->blockName != NULL)
725 xmlFree(range->blockName);
731 * @ctxt: the regexp parser context
732 * @type: the type of atom
734 * Allocate a new regexp range
736 * Returns the new atom or NULL in case of error
739 xmlRegNewAtom(xmlRegParserCtxtPtr ctxt, xmlRegAtomType type) {
742 ret = (xmlRegAtomPtr) xmlMalloc(sizeof(xmlRegAtom));
744 xmlRegexpErrMemory(ctxt, "allocating atom");
747 memset(ret, 0, sizeof(xmlRegAtom));
749 ret->quant = XML_REGEXP_QUANT_ONCE;
757 * @atom: the regexp atom
762 xmlRegFreeAtom(xmlRegAtomPtr atom) {
768 for (i = 0;i < atom->nbRanges;i++)
769 xmlRegFreeRange(atom->ranges[i]);
770 if (atom->ranges != NULL)
771 xmlFree(atom->ranges);
772 if ((atom->type == XML_REGEXP_STRING) && (atom->valuep != NULL))
773 xmlFree(atom->valuep);
774 if ((atom->type == XML_REGEXP_STRING) && (atom->valuep2 != NULL))
775 xmlFree(atom->valuep2);
776 if ((atom->type == XML_REGEXP_BLOCK_NAME) && (atom->valuep != NULL))
777 xmlFree(atom->valuep);
781 static xmlRegStatePtr
782 xmlRegNewState(xmlRegParserCtxtPtr ctxt) {
785 ret = (xmlRegStatePtr) xmlMalloc(sizeof(xmlRegState));
787 xmlRegexpErrMemory(ctxt, "allocating state");
790 memset(ret, 0, sizeof(xmlRegState));
791 ret->type = XML_REGEXP_TRANS_STATE;
792 ret->mark = XML_REGEXP_MARK_NORMAL;
798 * @state: the regexp state
800 * Free a regexp state
803 xmlRegFreeState(xmlRegStatePtr state) {
807 if (state->trans != NULL)
808 xmlFree(state->trans);
809 if (state->transTo != NULL)
810 xmlFree(state->transTo);
815 * xmlRegFreeParserCtxt:
816 * @ctxt: the regexp parser context
818 * Free a regexp parser context
821 xmlRegFreeParserCtxt(xmlRegParserCtxtPtr ctxt) {
826 if (ctxt->string != NULL)
827 xmlFree(ctxt->string);
828 if (ctxt->states != NULL) {
829 for (i = 0;i < ctxt->nbStates;i++)
830 xmlRegFreeState(ctxt->states[i]);
831 xmlFree(ctxt->states);
833 if (ctxt->atoms != NULL) {
834 for (i = 0;i < ctxt->nbAtoms;i++)
835 xmlRegFreeAtom(ctxt->atoms[i]);
836 xmlFree(ctxt->atoms);
838 if (ctxt->counters != NULL)
839 xmlFree(ctxt->counters);
843 /************************************************************************
845 * Display of Data structures *
847 ************************************************************************/
850 xmlRegPrintAtomType(FILE *output, xmlRegAtomType type) {
852 case XML_REGEXP_EPSILON:
853 fprintf(output, "epsilon "); break;
854 case XML_REGEXP_CHARVAL:
855 fprintf(output, "charval "); break;
856 case XML_REGEXP_RANGES:
857 fprintf(output, "ranges "); break;
858 case XML_REGEXP_SUBREG:
859 fprintf(output, "subexpr "); break;
860 case XML_REGEXP_STRING:
861 fprintf(output, "string "); break;
862 case XML_REGEXP_ANYCHAR:
863 fprintf(output, "anychar "); break;
864 case XML_REGEXP_ANYSPACE:
865 fprintf(output, "anyspace "); break;
866 case XML_REGEXP_NOTSPACE:
867 fprintf(output, "notspace "); break;
868 case XML_REGEXP_INITNAME:
869 fprintf(output, "initname "); break;
870 case XML_REGEXP_NOTINITNAME:
871 fprintf(output, "notinitname "); break;
872 case XML_REGEXP_NAMECHAR:
873 fprintf(output, "namechar "); break;
874 case XML_REGEXP_NOTNAMECHAR:
875 fprintf(output, "notnamechar "); break;
876 case XML_REGEXP_DECIMAL:
877 fprintf(output, "decimal "); break;
878 case XML_REGEXP_NOTDECIMAL:
879 fprintf(output, "notdecimal "); break;
880 case XML_REGEXP_REALCHAR:
881 fprintf(output, "realchar "); break;
882 case XML_REGEXP_NOTREALCHAR:
883 fprintf(output, "notrealchar "); break;
884 case XML_REGEXP_LETTER:
885 fprintf(output, "LETTER "); break;
886 case XML_REGEXP_LETTER_UPPERCASE:
887 fprintf(output, "LETTER_UPPERCASE "); break;
888 case XML_REGEXP_LETTER_LOWERCASE:
889 fprintf(output, "LETTER_LOWERCASE "); break;
890 case XML_REGEXP_LETTER_TITLECASE:
891 fprintf(output, "LETTER_TITLECASE "); break;
892 case XML_REGEXP_LETTER_MODIFIER:
893 fprintf(output, "LETTER_MODIFIER "); break;
894 case XML_REGEXP_LETTER_OTHERS:
895 fprintf(output, "LETTER_OTHERS "); break;
896 case XML_REGEXP_MARK:
897 fprintf(output, "MARK "); break;
898 case XML_REGEXP_MARK_NONSPACING:
899 fprintf(output, "MARK_NONSPACING "); break;
900 case XML_REGEXP_MARK_SPACECOMBINING:
901 fprintf(output, "MARK_SPACECOMBINING "); break;
902 case XML_REGEXP_MARK_ENCLOSING:
903 fprintf(output, "MARK_ENCLOSING "); break;
904 case XML_REGEXP_NUMBER:
905 fprintf(output, "NUMBER "); break;
906 case XML_REGEXP_NUMBER_DECIMAL:
907 fprintf(output, "NUMBER_DECIMAL "); break;
908 case XML_REGEXP_NUMBER_LETTER:
909 fprintf(output, "NUMBER_LETTER "); break;
910 case XML_REGEXP_NUMBER_OTHERS:
911 fprintf(output, "NUMBER_OTHERS "); break;
912 case XML_REGEXP_PUNCT:
913 fprintf(output, "PUNCT "); break;
914 case XML_REGEXP_PUNCT_CONNECTOR:
915 fprintf(output, "PUNCT_CONNECTOR "); break;
916 case XML_REGEXP_PUNCT_DASH:
917 fprintf(output, "PUNCT_DASH "); break;
918 case XML_REGEXP_PUNCT_OPEN:
919 fprintf(output, "PUNCT_OPEN "); break;
920 case XML_REGEXP_PUNCT_CLOSE:
921 fprintf(output, "PUNCT_CLOSE "); break;
922 case XML_REGEXP_PUNCT_INITQUOTE:
923 fprintf(output, "PUNCT_INITQUOTE "); break;
924 case XML_REGEXP_PUNCT_FINQUOTE:
925 fprintf(output, "PUNCT_FINQUOTE "); break;
926 case XML_REGEXP_PUNCT_OTHERS:
927 fprintf(output, "PUNCT_OTHERS "); break;
928 case XML_REGEXP_SEPAR:
929 fprintf(output, "SEPAR "); break;
930 case XML_REGEXP_SEPAR_SPACE:
931 fprintf(output, "SEPAR_SPACE "); break;
932 case XML_REGEXP_SEPAR_LINE:
933 fprintf(output, "SEPAR_LINE "); break;
934 case XML_REGEXP_SEPAR_PARA:
935 fprintf(output, "SEPAR_PARA "); break;
936 case XML_REGEXP_SYMBOL:
937 fprintf(output, "SYMBOL "); break;
938 case XML_REGEXP_SYMBOL_MATH:
939 fprintf(output, "SYMBOL_MATH "); break;
940 case XML_REGEXP_SYMBOL_CURRENCY:
941 fprintf(output, "SYMBOL_CURRENCY "); break;
942 case XML_REGEXP_SYMBOL_MODIFIER:
943 fprintf(output, "SYMBOL_MODIFIER "); break;
944 case XML_REGEXP_SYMBOL_OTHERS:
945 fprintf(output, "SYMBOL_OTHERS "); break;
946 case XML_REGEXP_OTHER:
947 fprintf(output, "OTHER "); break;
948 case XML_REGEXP_OTHER_CONTROL:
949 fprintf(output, "OTHER_CONTROL "); break;
950 case XML_REGEXP_OTHER_FORMAT:
951 fprintf(output, "OTHER_FORMAT "); break;
952 case XML_REGEXP_OTHER_PRIVATE:
953 fprintf(output, "OTHER_PRIVATE "); break;
954 case XML_REGEXP_OTHER_NA:
955 fprintf(output, "OTHER_NA "); break;
956 case XML_REGEXP_BLOCK_NAME:
957 fprintf(output, "BLOCK "); break;
962 xmlRegPrintQuantType(FILE *output, xmlRegQuantType type) {
964 case XML_REGEXP_QUANT_EPSILON:
965 fprintf(output, "epsilon "); break;
966 case XML_REGEXP_QUANT_ONCE:
967 fprintf(output, "once "); break;
968 case XML_REGEXP_QUANT_OPT:
969 fprintf(output, "? "); break;
970 case XML_REGEXP_QUANT_MULT:
971 fprintf(output, "* "); break;
972 case XML_REGEXP_QUANT_PLUS:
973 fprintf(output, "+ "); break;
974 case XML_REGEXP_QUANT_RANGE:
975 fprintf(output, "range "); break;
976 case XML_REGEXP_QUANT_ONCEONLY:
977 fprintf(output, "onceonly "); break;
978 case XML_REGEXP_QUANT_ALL:
979 fprintf(output, "all "); break;
983 xmlRegPrintRange(FILE *output, xmlRegRangePtr range) {
984 fprintf(output, " range: ");
986 fprintf(output, "negative ");
987 xmlRegPrintAtomType(output, range->type);
988 fprintf(output, "%c - %c\n", range->start, range->end);
992 xmlRegPrintAtom(FILE *output, xmlRegAtomPtr atom) {
993 fprintf(output, " atom: ");
995 fprintf(output, "NULL\n");
999 fprintf(output, "not ");
1000 xmlRegPrintAtomType(output, atom->type);
1001 xmlRegPrintQuantType(output, atom->quant);
1002 if (atom->quant == XML_REGEXP_QUANT_RANGE)
1003 fprintf(output, "%d-%d ", atom->min, atom->max);
1004 if (atom->type == XML_REGEXP_STRING)
1005 fprintf(output, "'%s' ", (char *) atom->valuep);
1006 if (atom->type == XML_REGEXP_CHARVAL)
1007 fprintf(output, "char %c\n", atom->codepoint);
1008 else if (atom->type == XML_REGEXP_RANGES) {
1010 fprintf(output, "%d entries\n", atom->nbRanges);
1011 for (i = 0; i < atom->nbRanges;i++)
1012 xmlRegPrintRange(output, atom->ranges[i]);
1013 } else if (atom->type == XML_REGEXP_SUBREG) {
1014 fprintf(output, "start %d end %d\n", atom->start->no, atom->stop->no);
1016 fprintf(output, "\n");
1021 xmlRegPrintTrans(FILE *output, xmlRegTransPtr trans) {
1022 fprintf(output, " trans: ");
1023 if (trans == NULL) {
1024 fprintf(output, "NULL\n");
1027 if (trans->to < 0) {
1028 fprintf(output, "removed\n");
1031 if (trans->nd != 0) {
1033 fprintf(output, "last not determinist, ");
1035 fprintf(output, "not determinist, ");
1037 if (trans->counter >= 0) {
1038 fprintf(output, "counted %d, ", trans->counter);
1040 if (trans->count == REGEXP_ALL_COUNTER) {
1041 fprintf(output, "all transition, ");
1042 } else if (trans->count >= 0) {
1043 fprintf(output, "count based %d, ", trans->count);
1045 if (trans->atom == NULL) {
1046 fprintf(output, "epsilon to %d\n", trans->to);
1049 if (trans->atom->type == XML_REGEXP_CHARVAL)
1050 fprintf(output, "char %c ", trans->atom->codepoint);
1051 fprintf(output, "atom %d, to %d\n", trans->atom->no, trans->to);
1055 xmlRegPrintState(FILE *output, xmlRegStatePtr state) {
1058 fprintf(output, " state: ");
1059 if (state == NULL) {
1060 fprintf(output, "NULL\n");
1063 if (state->type == XML_REGEXP_START_STATE)
1064 fprintf(output, "START ");
1065 if (state->type == XML_REGEXP_FINAL_STATE)
1066 fprintf(output, "FINAL ");
1068 fprintf(output, "%d, %d transitions:\n", state->no, state->nbTrans);
1069 for (i = 0;i < state->nbTrans; i++) {
1070 xmlRegPrintTrans(output, &(state->trans[i]));
1074 #ifdef DEBUG_REGEXP_GRAPH
1076 xmlRegPrintCtxt(FILE *output, xmlRegParserCtxtPtr ctxt) {
1079 fprintf(output, " ctxt: ");
1081 fprintf(output, "NULL\n");
1084 fprintf(output, "'%s' ", ctxt->string);
1086 fprintf(output, "error ");
1088 fprintf(output, "neg ");
1089 fprintf(output, "\n");
1090 fprintf(output, "%d atoms:\n", ctxt->nbAtoms);
1091 for (i = 0;i < ctxt->nbAtoms; i++) {
1092 fprintf(output, " %02d ", i);
1093 xmlRegPrintAtom(output, ctxt->atoms[i]);
1095 if (ctxt->atom != NULL) {
1096 fprintf(output, "current atom:\n");
1097 xmlRegPrintAtom(output, ctxt->atom);
1099 fprintf(output, "%d states:", ctxt->nbStates);
1100 if (ctxt->start != NULL)
1101 fprintf(output, " start: %d", ctxt->start->no);
1102 if (ctxt->end != NULL)
1103 fprintf(output, " end: %d", ctxt->end->no);
1104 fprintf(output, "\n");
1105 for (i = 0;i < ctxt->nbStates; i++) {
1106 xmlRegPrintState(output, ctxt->states[i]);
1108 fprintf(output, "%d counters:\n", ctxt->nbCounters);
1109 for (i = 0;i < ctxt->nbCounters; i++) {
1110 fprintf(output, " %d: min %d max %d\n", i, ctxt->counters[i].min,
1111 ctxt->counters[i].max);
1116 /************************************************************************
1118 * Finite Automata structures manipulations *
1120 ************************************************************************/
1123 xmlRegAtomAddRange(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom,
1124 int neg, xmlRegAtomType type, int start, int end,
1125 xmlChar *blockName) {
1126 xmlRegRangePtr range;
1129 ERROR("add range: atom is NULL");
1132 if (atom->type != XML_REGEXP_RANGES) {
1133 ERROR("add range: atom is not ranges");
1136 if (atom->maxRanges == 0) {
1137 atom->maxRanges = 4;
1138 atom->ranges = (xmlRegRangePtr *) xmlMalloc(atom->maxRanges *
1139 sizeof(xmlRegRangePtr));
1140 if (atom->ranges == NULL) {
1141 xmlRegexpErrMemory(ctxt, "adding ranges");
1142 atom->maxRanges = 0;
1145 } else if (atom->nbRanges >= atom->maxRanges) {
1146 xmlRegRangePtr *tmp;
1147 atom->maxRanges *= 2;
1148 tmp = (xmlRegRangePtr *) xmlRealloc(atom->ranges, atom->maxRanges *
1149 sizeof(xmlRegRangePtr));
1151 xmlRegexpErrMemory(ctxt, "adding ranges");
1152 atom->maxRanges /= 2;
1157 range = xmlRegNewRange(ctxt, neg, type, start, end);
1160 range->blockName = blockName;
1161 atom->ranges[atom->nbRanges++] = range;
1166 xmlRegGetCounter(xmlRegParserCtxtPtr ctxt) {
1167 if (ctxt->maxCounters == 0) {
1168 ctxt->maxCounters = 4;
1169 ctxt->counters = (xmlRegCounter *) xmlMalloc(ctxt->maxCounters *
1170 sizeof(xmlRegCounter));
1171 if (ctxt->counters == NULL) {
1172 xmlRegexpErrMemory(ctxt, "allocating counter");
1173 ctxt->maxCounters = 0;
1176 } else if (ctxt->nbCounters >= ctxt->maxCounters) {
1178 ctxt->maxCounters *= 2;
1179 tmp = (xmlRegCounter *) xmlRealloc(ctxt->counters, ctxt->maxCounters *
1180 sizeof(xmlRegCounter));
1182 xmlRegexpErrMemory(ctxt, "allocating counter");
1183 ctxt->maxCounters /= 2;
1186 ctxt->counters = tmp;
1188 ctxt->counters[ctxt->nbCounters].min = -1;
1189 ctxt->counters[ctxt->nbCounters].max = -1;
1190 return(ctxt->nbCounters++);
1194 xmlRegAtomPush(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom) {
1196 ERROR("atom push: atom is NULL");
1199 if (ctxt->maxAtoms == 0) {
1201 ctxt->atoms = (xmlRegAtomPtr *) xmlMalloc(ctxt->maxAtoms *
1202 sizeof(xmlRegAtomPtr));
1203 if (ctxt->atoms == NULL) {
1204 xmlRegexpErrMemory(ctxt, "pushing atom");
1208 } else if (ctxt->nbAtoms >= ctxt->maxAtoms) {
1210 ctxt->maxAtoms *= 2;
1211 tmp = (xmlRegAtomPtr *) xmlRealloc(ctxt->atoms, ctxt->maxAtoms *
1212 sizeof(xmlRegAtomPtr));
1214 xmlRegexpErrMemory(ctxt, "allocating counter");
1215 ctxt->maxAtoms /= 2;
1220 atom->no = ctxt->nbAtoms;
1221 ctxt->atoms[ctxt->nbAtoms++] = atom;
1226 xmlRegStateAddTransTo(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr target,
1228 if (target->maxTransTo == 0) {
1229 target->maxTransTo = 8;
1230 target->transTo = (int *) xmlMalloc(target->maxTransTo *
1232 if (target->transTo == NULL) {
1233 xmlRegexpErrMemory(ctxt, "adding transition");
1234 target->maxTransTo = 0;
1237 } else if (target->nbTransTo >= target->maxTransTo) {
1239 target->maxTransTo *= 2;
1240 tmp = (int *) xmlRealloc(target->transTo, target->maxTransTo *
1243 xmlRegexpErrMemory(ctxt, "adding transition");
1244 target->maxTransTo /= 2;
1247 target->transTo = tmp;
1249 target->transTo[target->nbTransTo] = from;
1250 target->nbTransTo++;
1254 xmlRegStateAddTrans(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state,
1255 xmlRegAtomPtr atom, xmlRegStatePtr target,
1256 int counter, int count) {
1260 if (state == NULL) {
1261 ERROR("add state: state is NULL");
1264 if (target == NULL) {
1265 ERROR("add state: target is NULL");
1269 * Other routines follow the philosophy 'When in doubt, add a transition'
1270 * so we check here whether such a transition is already present and, if
1271 * so, silently ignore this request.
1274 for (nrtrans = state->nbTrans - 1; nrtrans >= 0; nrtrans--) {
1275 xmlRegTransPtr trans = &(state->trans[nrtrans]);
1276 if ((trans->atom == atom) &&
1277 (trans->to == target->no) &&
1278 (trans->counter == counter) &&
1279 (trans->count == count)) {
1280 #ifdef DEBUG_REGEXP_GRAPH
1281 printf("Ignoring duplicate transition from %d to %d\n",
1282 state->no, target->no);
1288 if (state->maxTrans == 0) {
1289 state->maxTrans = 8;
1290 state->trans = (xmlRegTrans *) xmlMalloc(state->maxTrans *
1291 sizeof(xmlRegTrans));
1292 if (state->trans == NULL) {
1293 xmlRegexpErrMemory(ctxt, "adding transition");
1294 state->maxTrans = 0;
1297 } else if (state->nbTrans >= state->maxTrans) {
1299 state->maxTrans *= 2;
1300 tmp = (xmlRegTrans *) xmlRealloc(state->trans, state->maxTrans *
1301 sizeof(xmlRegTrans));
1303 xmlRegexpErrMemory(ctxt, "adding transition");
1304 state->maxTrans /= 2;
1309 #ifdef DEBUG_REGEXP_GRAPH
1310 printf("Add trans from %d to %d ", state->no, target->no);
1311 if (count == REGEXP_ALL_COUNTER)
1312 printf("all transition\n");
1313 else if (count >= 0)
1314 printf("count based %d\n", count);
1315 else if (counter >= 0)
1316 printf("counted %d\n", counter);
1317 else if (atom == NULL)
1318 printf("epsilon transition\n");
1319 else if (atom != NULL)
1320 xmlRegPrintAtom(stdout, atom);
1323 state->trans[state->nbTrans].atom = atom;
1324 state->trans[state->nbTrans].to = target->no;
1325 state->trans[state->nbTrans].counter = counter;
1326 state->trans[state->nbTrans].count = count;
1327 state->trans[state->nbTrans].nd = 0;
1329 xmlRegStateAddTransTo(ctxt, target, state->no);
1333 xmlRegStatePush(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state) {
1334 if (state == NULL) return(-1);
1335 if (ctxt->maxStates == 0) {
1336 ctxt->maxStates = 4;
1337 ctxt->states = (xmlRegStatePtr *) xmlMalloc(ctxt->maxStates *
1338 sizeof(xmlRegStatePtr));
1339 if (ctxt->states == NULL) {
1340 xmlRegexpErrMemory(ctxt, "adding state");
1341 ctxt->maxStates = 0;
1344 } else if (ctxt->nbStates >= ctxt->maxStates) {
1345 xmlRegStatePtr *tmp;
1346 ctxt->maxStates *= 2;
1347 tmp = (xmlRegStatePtr *) xmlRealloc(ctxt->states, ctxt->maxStates *
1348 sizeof(xmlRegStatePtr));
1350 xmlRegexpErrMemory(ctxt, "adding state");
1351 ctxt->maxStates /= 2;
1356 state->no = ctxt->nbStates;
1357 ctxt->states[ctxt->nbStates++] = state;
1362 * xmlFAGenerateAllTransition:
1363 * @ctxt: a regexp parser context
1364 * @from: the from state
1365 * @to: the target state or NULL for building a new one
1370 xmlFAGenerateAllTransition(xmlRegParserCtxtPtr ctxt,
1371 xmlRegStatePtr from, xmlRegStatePtr to,
1374 to = xmlRegNewState(ctxt);
1375 xmlRegStatePush(ctxt, to);
1379 xmlRegStateAddTrans(ctxt, from, NULL, to, -1, REGEXP_ALL_LAX_COUNTER);
1381 xmlRegStateAddTrans(ctxt, from, NULL, to, -1, REGEXP_ALL_COUNTER);
1385 * xmlFAGenerateEpsilonTransition:
1386 * @ctxt: a regexp parser context
1387 * @from: the from state
1388 * @to: the target state or NULL for building a new one
1392 xmlFAGenerateEpsilonTransition(xmlRegParserCtxtPtr ctxt,
1393 xmlRegStatePtr from, xmlRegStatePtr to) {
1395 to = xmlRegNewState(ctxt);
1396 xmlRegStatePush(ctxt, to);
1399 xmlRegStateAddTrans(ctxt, from, NULL, to, -1, -1);
1403 * xmlFAGenerateCountedEpsilonTransition:
1404 * @ctxt: a regexp parser context
1405 * @from: the from state
1406 * @to: the target state or NULL for building a new one
1407 * counter: the counter for that transition
1411 xmlFAGenerateCountedEpsilonTransition(xmlRegParserCtxtPtr ctxt,
1412 xmlRegStatePtr from, xmlRegStatePtr to, int counter) {
1414 to = xmlRegNewState(ctxt);
1415 xmlRegStatePush(ctxt, to);
1418 xmlRegStateAddTrans(ctxt, from, NULL, to, counter, -1);
1422 * xmlFAGenerateCountedTransition:
1423 * @ctxt: a regexp parser context
1424 * @from: the from state
1425 * @to: the target state or NULL for building a new one
1426 * counter: the counter for that transition
1430 xmlFAGenerateCountedTransition(xmlRegParserCtxtPtr ctxt,
1431 xmlRegStatePtr from, xmlRegStatePtr to, int counter) {
1433 to = xmlRegNewState(ctxt);
1434 xmlRegStatePush(ctxt, to);
1437 xmlRegStateAddTrans(ctxt, from, NULL, to, -1, counter);
1441 * xmlFAGenerateTransitions:
1442 * @ctxt: a regexp parser context
1443 * @from: the from state
1444 * @to: the target state or NULL for building a new one
1445 * @atom: the atom generating the transition
1447 * Returns 0 if success and -1 in case of error.
1450 xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from,
1451 xmlRegStatePtr to, xmlRegAtomPtr atom) {
1453 ERROR("genrate transition: atom == NULL");
1456 if (atom->type == XML_REGEXP_SUBREG) {
1458 * this is a subexpression handling one should not need to
1459 * create a new node except for XML_REGEXP_QUANT_RANGE.
1461 if (xmlRegAtomPush(ctxt, atom) < 0) {
1464 if ((to != NULL) && (atom->stop != to) &&
1465 (atom->quant != XML_REGEXP_QUANT_RANGE)) {
1467 * Generate an epsilon transition to link to the target
1469 xmlFAGenerateEpsilonTransition(ctxt, atom->stop, to);
1471 } else if ((to == NULL) && (atom->quant != XML_REGEXP_QUANT_RANGE) &&
1472 (atom->quant != XML_REGEXP_QUANT_ONCE)) {
1473 to = xmlRegNewState(ctxt);
1474 xmlRegStatePush(ctxt, to);
1476 xmlFAGenerateEpsilonTransition(ctxt, atom->stop, to);
1479 switch (atom->quant) {
1480 case XML_REGEXP_QUANT_OPT:
1481 atom->quant = XML_REGEXP_QUANT_ONCE;
1483 * transition done to the state after end of atom.
1484 * 1. set transition from atom start to new state
1485 * 2. set transition from atom end to this state.
1487 xmlFAGenerateEpsilonTransition(ctxt, atom->start, 0);
1488 xmlFAGenerateEpsilonTransition(ctxt, atom->stop, ctxt->state);
1490 case XML_REGEXP_QUANT_MULT:
1491 atom->quant = XML_REGEXP_QUANT_ONCE;
1492 xmlFAGenerateEpsilonTransition(ctxt, atom->start, atom->stop);
1493 xmlFAGenerateEpsilonTransition(ctxt, atom->stop, atom->start);
1495 case XML_REGEXP_QUANT_PLUS:
1496 atom->quant = XML_REGEXP_QUANT_ONCE;
1497 xmlFAGenerateEpsilonTransition(ctxt, atom->stop, atom->start);
1499 case XML_REGEXP_QUANT_RANGE: {
1501 xmlRegStatePtr newstate;
1504 * This one is nasty:
1505 * 1/ if range has minOccurs == 0, create a new state
1506 * and create epsilon transitions from atom->start
1507 * to atom->stop, as well as atom->start to the new
1509 * 2/ register a new counter
1510 * 3/ register an epsilon transition associated to
1511 * this counter going from atom->stop to atom->start
1512 * 4/ create a new state
1513 * 5/ generate a counted transition from atom->stop to
1516 if (atom->min == 0) {
1517 xmlFAGenerateEpsilonTransition(ctxt, atom->start,
1519 newstate = xmlRegNewState(ctxt);
1520 xmlRegStatePush(ctxt, newstate);
1521 ctxt->state = newstate;
1522 xmlFAGenerateEpsilonTransition(ctxt, atom->start,
1525 counter = xmlRegGetCounter(ctxt);
1526 ctxt->counters[counter].min = atom->min - 1;
1527 ctxt->counters[counter].max = atom->max - 1;
1530 atom->quant = XML_REGEXP_QUANT_ONCE;
1534 newstate = xmlRegNewState(ctxt);
1535 xmlRegStatePush(ctxt, newstate);
1537 ctxt->state = newstate;
1538 xmlFAGenerateCountedTransition(ctxt, atom->stop,
1542 * first check count and if OK jump forward;
1543 * if checking fail increment count and jump back
1545 xmlFAGenerateCountedEpsilonTransition(ctxt, atom->stop,
1546 atom->start, counter);
1553 if ((atom->min == 0) && (atom->max == 0) &&
1554 (atom->quant == XML_REGEXP_QUANT_RANGE)) {
1556 * we can discard the atom and generate an epsilon transition instead
1559 to = xmlRegNewState(ctxt);
1561 xmlRegStatePush(ctxt, to);
1566 xmlFAGenerateEpsilonTransition(ctxt, from, to);
1568 xmlRegFreeAtom(atom);
1572 to = xmlRegNewState(ctxt);
1574 xmlRegStatePush(ctxt, to);
1579 if (xmlRegAtomPush(ctxt, atom) < 0) {
1582 xmlRegStateAddTrans(ctxt, from, atom, to, -1, -1);
1584 switch (atom->quant) {
1585 case XML_REGEXP_QUANT_OPT:
1586 atom->quant = XML_REGEXP_QUANT_ONCE;
1587 xmlFAGenerateEpsilonTransition(ctxt, from, to);
1589 case XML_REGEXP_QUANT_MULT:
1590 atom->quant = XML_REGEXP_QUANT_ONCE;
1591 xmlFAGenerateEpsilonTransition(ctxt, from, to);
1592 xmlRegStateAddTrans(ctxt, to, atom, to, -1, -1);
1594 case XML_REGEXP_QUANT_PLUS:
1595 atom->quant = XML_REGEXP_QUANT_ONCE;
1596 xmlRegStateAddTrans(ctxt, to, atom, to, -1, -1);
1605 * xmlFAReduceEpsilonTransitions:
1606 * @ctxt: a regexp parser context
1607 * @fromnr: the from state
1608 * @tonr: the to state
1609 * @counter: should that transition be associated to a counted
1613 xmlFAReduceEpsilonTransitions(xmlRegParserCtxtPtr ctxt, int fromnr,
1614 int tonr, int counter) {
1616 xmlRegStatePtr from;
1619 #ifdef DEBUG_REGEXP_GRAPH
1620 printf("xmlFAReduceEpsilonTransitions(%d, %d)\n", fromnr, tonr);
1622 from = ctxt->states[fromnr];
1625 to = ctxt->states[tonr];
1628 if ((to->mark == XML_REGEXP_MARK_START) ||
1629 (to->mark == XML_REGEXP_MARK_VISITED))
1632 to->mark = XML_REGEXP_MARK_VISITED;
1633 if (to->type == XML_REGEXP_FINAL_STATE) {
1634 #ifdef DEBUG_REGEXP_GRAPH
1635 printf("State %d is final, so %d becomes final\n", tonr, fromnr);
1637 from->type = XML_REGEXP_FINAL_STATE;
1639 for (transnr = 0;transnr < to->nbTrans;transnr++) {
1640 if (to->trans[transnr].to < 0)
1642 if (to->trans[transnr].atom == NULL) {
1644 * Don't remove counted transitions
1647 if (to->trans[transnr].to != fromnr) {
1648 if (to->trans[transnr].count >= 0) {
1649 int newto = to->trans[transnr].to;
1651 xmlRegStateAddTrans(ctxt, from, NULL,
1652 ctxt->states[newto],
1653 -1, to->trans[transnr].count);
1655 #ifdef DEBUG_REGEXP_GRAPH
1656 printf("Found epsilon trans %d from %d to %d\n",
1657 transnr, tonr, to->trans[transnr].to);
1659 if (to->trans[transnr].counter >= 0) {
1660 xmlFAReduceEpsilonTransitions(ctxt, fromnr,
1661 to->trans[transnr].to,
1662 to->trans[transnr].counter);
1664 xmlFAReduceEpsilonTransitions(ctxt, fromnr,
1665 to->trans[transnr].to,
1671 int newto = to->trans[transnr].to;
1673 if (to->trans[transnr].counter >= 0) {
1674 xmlRegStateAddTrans(ctxt, from, to->trans[transnr].atom,
1675 ctxt->states[newto],
1676 to->trans[transnr].counter, -1);
1678 xmlRegStateAddTrans(ctxt, from, to->trans[transnr].atom,
1679 ctxt->states[newto], counter, -1);
1683 to->mark = XML_REGEXP_MARK_NORMAL;
1687 * xmlFAEliminateSimpleEpsilonTransitions:
1688 * @ctxt: a regexp parser context
1690 * Eliminating general epsilon transitions can get costly in the general
1691 * algorithm due to the large amount of generated new transitions and
1692 * associated comparisons. However for simple epsilon transition used just
1693 * to separate building blocks when generating the automata this can be
1694 * reduced to state elimination:
1695 * - if there exists an epsilon from X to Y
1696 * - if there is no other transition from X
1697 * then X and Y are semantically equivalent and X can be eliminated
1698 * If X is the start state then make Y the start state, else replace the
1699 * target of all transitions to X by transitions to Y.
1702 xmlFAEliminateSimpleEpsilonTransitions(xmlRegParserCtxtPtr ctxt) {
1703 int statenr, i, j, newto;
1704 xmlRegStatePtr state, tmp;
1706 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1707 state = ctxt->states[statenr];
1710 if (state->nbTrans != 1)
1712 /* is the only transition out a basic transition */
1713 if ((state->trans[0].atom == NULL) &&
1714 (state->trans[0].to >= 0) &&
1715 (state->trans[0].to != statenr) &&
1716 (state->trans[0].counter < 0) &&
1717 (state->trans[0].count < 0)) {
1718 newto = state->trans[0].to;
1720 if (state->type == XML_REGEXP_START_STATE) {
1721 #ifdef DEBUG_REGEXP_GRAPH
1722 printf("Found simple epsilon trans from start %d to %d\n",
1726 #ifdef DEBUG_REGEXP_GRAPH
1727 printf("Found simple epsilon trans from %d to %d\n",
1730 for (i = 0;i < state->nbTransTo;i++) {
1731 tmp = ctxt->states[state->transTo[i]];
1732 for (j = 0;j < tmp->nbTrans;j++) {
1733 if (tmp->trans[j].to == statenr) {
1734 tmp->trans[j].to = newto;
1735 #ifdef DEBUG_REGEXP_GRAPH
1736 printf("Changed transition %d on %d to go to %d\n",
1739 xmlRegStateAddTransTo(ctxt, ctxt->states[newto],
1745 for (i = 0;i < ctxt->nbStates;i++) {
1746 tmp = ctxt->states[i];
1747 for (j = 0;j < tmp->nbTrans;j++) {
1748 if (tmp->trans[j].to == statenr) {
1749 tmp->trans[j].to = newto;
1750 #ifdef DEBUG_REGEXP_GRAPH
1751 printf("Changed transition %d on %d to go to %d\n",
1758 if (state->type == XML_REGEXP_FINAL_STATE)
1759 ctxt->states[newto]->type = XML_REGEXP_FINAL_STATE;
1760 /* eliminate the transition completely */
1770 * xmlFAEliminateEpsilonTransitions:
1771 * @ctxt: a regexp parser context
1775 xmlFAEliminateEpsilonTransitions(xmlRegParserCtxtPtr ctxt) {
1776 int statenr, transnr;
1777 xmlRegStatePtr state;
1780 if (ctxt->states == NULL) return;
1782 xmlFAEliminateSimpleEpsilonTransitions(ctxt);
1787 * build the completed transitions bypassing the epsilons
1788 * Use a marking algorithm to avoid loops
1789 * mark sink states too.
1791 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1792 state = ctxt->states[statenr];
1795 if ((state->nbTrans == 0) &&
1796 (state->type != XML_REGEXP_FINAL_STATE)) {
1797 state->type = XML_REGEXP_SINK_STATE;
1799 for (transnr = 0;transnr < state->nbTrans;transnr++) {
1800 if ((state->trans[transnr].atom == NULL) &&
1801 (state->trans[transnr].to >= 0)) {
1802 if (state->trans[transnr].to == statenr) {
1803 state->trans[transnr].to = -1;
1804 #ifdef DEBUG_REGEXP_GRAPH
1805 printf("Removed loopback epsilon trans %d on %d\n",
1808 } else if (state->trans[transnr].count < 0) {
1809 int newto = state->trans[transnr].to;
1811 #ifdef DEBUG_REGEXP_GRAPH
1812 printf("Found epsilon trans %d from %d to %d\n",
1813 transnr, statenr, newto);
1815 state->mark = XML_REGEXP_MARK_START;
1817 xmlFAReduceEpsilonTransitions(ctxt, statenr,
1818 newto, state->trans[transnr].counter);
1819 state->mark = XML_REGEXP_MARK_NORMAL;
1820 #ifdef DEBUG_REGEXP_GRAPH
1822 printf("Found counted transition %d on %d\n",
1830 * Eliminate the epsilon transitions
1833 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1834 state = ctxt->states[statenr];
1837 for (transnr = 0;transnr < state->nbTrans;transnr++) {
1838 xmlRegTransPtr trans = &(state->trans[transnr]);
1839 if ((trans->atom == NULL) &&
1840 (trans->count < 0) &&
1849 * Use this pass to detect unreachable states too
1851 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1852 state = ctxt->states[statenr];
1854 state->reached = XML_REGEXP_MARK_NORMAL;
1856 state = ctxt->states[0];
1858 state->reached = XML_REGEXP_MARK_START;
1859 while (state != NULL) {
1860 xmlRegStatePtr target = NULL;
1861 state->reached = XML_REGEXP_MARK_VISITED;
1863 * Mark all states reachable from the current reachable state
1865 for (transnr = 0;transnr < state->nbTrans;transnr++) {
1866 if ((state->trans[transnr].to >= 0) &&
1867 ((state->trans[transnr].atom != NULL) ||
1868 (state->trans[transnr].count >= 0))) {
1869 int newto = state->trans[transnr].to;
1871 if (ctxt->states[newto] == NULL)
1873 if (ctxt->states[newto]->reached == XML_REGEXP_MARK_NORMAL) {
1874 ctxt->states[newto]->reached = XML_REGEXP_MARK_START;
1875 target = ctxt->states[newto];
1881 * find the next accessible state not explored
1883 if (target == NULL) {
1884 for (statenr = 1;statenr < ctxt->nbStates;statenr++) {
1885 state = ctxt->states[statenr];
1886 if ((state != NULL) && (state->reached ==
1887 XML_REGEXP_MARK_START)) {
1895 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1896 state = ctxt->states[statenr];
1897 if ((state != NULL) && (state->reached == XML_REGEXP_MARK_NORMAL)) {
1898 #ifdef DEBUG_REGEXP_GRAPH
1899 printf("Removed unreachable state %d\n", statenr);
1901 xmlRegFreeState(state);
1902 ctxt->states[statenr] = NULL;
1909 xmlFACompareRanges(xmlRegRangePtr range1, xmlRegRangePtr range2) {
1912 if ((range1->type == XML_REGEXP_RANGES) ||
1913 (range2->type == XML_REGEXP_RANGES) ||
1914 (range2->type == XML_REGEXP_SUBREG) ||
1915 (range1->type == XML_REGEXP_SUBREG) ||
1916 (range1->type == XML_REGEXP_STRING) ||
1917 (range2->type == XML_REGEXP_STRING))
1920 /* put them in order */
1921 if (range1->type > range2->type) {
1928 if ((range1->type == XML_REGEXP_ANYCHAR) ||
1929 (range2->type == XML_REGEXP_ANYCHAR)) {
1931 } else if ((range1->type == XML_REGEXP_EPSILON) ||
1932 (range2->type == XML_REGEXP_EPSILON)) {
1934 } else if (range1->type == range2->type) {
1935 if ((range1->type != XML_REGEXP_CHARVAL) ||
1936 (range1->end < range2->start) ||
1937 (range2->end < range1->start))
1941 } else if (range1->type == XML_REGEXP_CHARVAL) {
1946 * just check all codepoints in the range for acceptance,
1947 * this is usually way cheaper since done only once at
1948 * compilation than testing over and over at runtime or
1949 * pushing too many states when evaluating.
1951 if (((range1->neg == 0) && (range2->neg != 0)) ||
1952 ((range1->neg != 0) && (range2->neg == 0)))
1955 for (codepoint = range1->start;codepoint <= range1->end ;codepoint++) {
1956 ret = xmlRegCheckCharacterRange(range2->type, codepoint,
1957 0, range2->start, range2->end,
1961 if (((neg == 1) && (ret == 0)) ||
1962 ((neg == 0) && (ret == 1)))
1966 } else if ((range1->type == XML_REGEXP_BLOCK_NAME) ||
1967 (range2->type == XML_REGEXP_BLOCK_NAME)) {
1968 if (range1->type == range2->type) {
1969 ret = xmlStrEqual(range1->blockName, range2->blockName);
1972 * comparing a block range with anything else is way
1973 * too costly, and maintining the table is like too much
1974 * memory too, so let's force the automata to save state
1979 } else if ((range1->type < XML_REGEXP_LETTER) ||
1980 (range2->type < XML_REGEXP_LETTER)) {
1981 if ((range1->type == XML_REGEXP_ANYSPACE) &&
1982 (range2->type == XML_REGEXP_NOTSPACE))
1984 else if ((range1->type == XML_REGEXP_INITNAME) &&
1985 (range2->type == XML_REGEXP_NOTINITNAME))
1987 else if ((range1->type == XML_REGEXP_NAMECHAR) &&
1988 (range2->type == XML_REGEXP_NOTNAMECHAR))
1990 else if ((range1->type == XML_REGEXP_DECIMAL) &&
1991 (range2->type == XML_REGEXP_NOTDECIMAL))
1993 else if ((range1->type == XML_REGEXP_REALCHAR) &&
1994 (range2->type == XML_REGEXP_NOTREALCHAR))
1997 /* same thing to limit complexity */
2002 /* range1->type < range2->type here */
2003 switch (range1->type) {
2004 case XML_REGEXP_LETTER:
2005 /* all disjoint except in the subgroups */
2006 if ((range2->type == XML_REGEXP_LETTER_UPPERCASE) ||
2007 (range2->type == XML_REGEXP_LETTER_LOWERCASE) ||
2008 (range2->type == XML_REGEXP_LETTER_TITLECASE) ||
2009 (range2->type == XML_REGEXP_LETTER_MODIFIER) ||
2010 (range2->type == XML_REGEXP_LETTER_OTHERS))
2013 case XML_REGEXP_MARK:
2014 if ((range2->type == XML_REGEXP_MARK_NONSPACING) ||
2015 (range2->type == XML_REGEXP_MARK_SPACECOMBINING) ||
2016 (range2->type == XML_REGEXP_MARK_ENCLOSING))
2019 case XML_REGEXP_NUMBER:
2020 if ((range2->type == XML_REGEXP_NUMBER_DECIMAL) ||
2021 (range2->type == XML_REGEXP_NUMBER_LETTER) ||
2022 (range2->type == XML_REGEXP_NUMBER_OTHERS))
2025 case XML_REGEXP_PUNCT:
2026 if ((range2->type == XML_REGEXP_PUNCT_CONNECTOR) ||
2027 (range2->type == XML_REGEXP_PUNCT_DASH) ||
2028 (range2->type == XML_REGEXP_PUNCT_OPEN) ||
2029 (range2->type == XML_REGEXP_PUNCT_CLOSE) ||
2030 (range2->type == XML_REGEXP_PUNCT_INITQUOTE) ||
2031 (range2->type == XML_REGEXP_PUNCT_FINQUOTE) ||
2032 (range2->type == XML_REGEXP_PUNCT_OTHERS))
2035 case XML_REGEXP_SEPAR:
2036 if ((range2->type == XML_REGEXP_SEPAR_SPACE) ||
2037 (range2->type == XML_REGEXP_SEPAR_LINE) ||
2038 (range2->type == XML_REGEXP_SEPAR_PARA))
2041 case XML_REGEXP_SYMBOL:
2042 if ((range2->type == XML_REGEXP_SYMBOL_MATH) ||
2043 (range2->type == XML_REGEXP_SYMBOL_CURRENCY) ||
2044 (range2->type == XML_REGEXP_SYMBOL_MODIFIER) ||
2045 (range2->type == XML_REGEXP_SYMBOL_OTHERS))
2048 case XML_REGEXP_OTHER:
2049 if ((range2->type == XML_REGEXP_OTHER_CONTROL) ||
2050 (range2->type == XML_REGEXP_OTHER_FORMAT) ||
2051 (range2->type == XML_REGEXP_OTHER_PRIVATE))
2055 if ((range2->type >= XML_REGEXP_LETTER) &&
2056 (range2->type < XML_REGEXP_BLOCK_NAME))
2064 if (((range1->neg == 0) && (range2->neg != 0)) ||
2065 ((range1->neg != 0) && (range2->neg == 0)))
2071 * xmlFACompareAtomTypes:
2072 * @type1: an atom type
2073 * @type2: an atom type
2075 * Compares two atoms type to check whether they intersect in some ways,
2076 * this is used by xmlFACompareAtoms only
2078 * Returns 1 if they may intersect and 0 otherwise
2081 xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
2082 if ((type1 == XML_REGEXP_EPSILON) ||
2083 (type1 == XML_REGEXP_CHARVAL) ||
2084 (type1 == XML_REGEXP_RANGES) ||
2085 (type1 == XML_REGEXP_SUBREG) ||
2086 (type1 == XML_REGEXP_STRING) ||
2087 (type1 == XML_REGEXP_ANYCHAR))
2089 if ((type2 == XML_REGEXP_EPSILON) ||
2090 (type2 == XML_REGEXP_CHARVAL) ||
2091 (type2 == XML_REGEXP_RANGES) ||
2092 (type2 == XML_REGEXP_SUBREG) ||
2093 (type2 == XML_REGEXP_STRING) ||
2094 (type2 == XML_REGEXP_ANYCHAR))
2097 if (type1 == type2) return(1);
2099 /* simplify subsequent compares by making sure type1 < type2 */
2100 if (type1 > type2) {
2101 xmlRegAtomType tmp = type1;
2106 case XML_REGEXP_ANYSPACE: /* \s */
2107 /* can't be a letter, number, mark, pontuation, symbol */
2108 if ((type2 == XML_REGEXP_NOTSPACE) ||
2109 ((type2 >= XML_REGEXP_LETTER) &&
2110 (type2 <= XML_REGEXP_LETTER_OTHERS)) ||
2111 ((type2 >= XML_REGEXP_NUMBER) &&
2112 (type2 <= XML_REGEXP_NUMBER_OTHERS)) ||
2113 ((type2 >= XML_REGEXP_MARK) &&
2114 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2115 ((type2 >= XML_REGEXP_PUNCT) &&
2116 (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2117 ((type2 >= XML_REGEXP_SYMBOL) &&
2118 (type2 <= XML_REGEXP_SYMBOL_OTHERS))
2121 case XML_REGEXP_NOTSPACE: /* \S */
2123 case XML_REGEXP_INITNAME: /* \l */
2124 /* can't be a number, mark, separator, pontuation, symbol or other */
2125 if ((type2 == XML_REGEXP_NOTINITNAME) ||
2126 ((type2 >= XML_REGEXP_NUMBER) &&
2127 (type2 <= XML_REGEXP_NUMBER_OTHERS)) ||
2128 ((type2 >= XML_REGEXP_MARK) &&
2129 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2130 ((type2 >= XML_REGEXP_SEPAR) &&
2131 (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2132 ((type2 >= XML_REGEXP_PUNCT) &&
2133 (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2134 ((type2 >= XML_REGEXP_SYMBOL) &&
2135 (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2136 ((type2 >= XML_REGEXP_OTHER) &&
2137 (type2 <= XML_REGEXP_OTHER_NA))
2140 case XML_REGEXP_NOTINITNAME: /* \L */
2142 case XML_REGEXP_NAMECHAR: /* \c */
2143 /* can't be a mark, separator, pontuation, symbol or other */
2144 if ((type2 == XML_REGEXP_NOTNAMECHAR) ||
2145 ((type2 >= XML_REGEXP_MARK) &&
2146 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2147 ((type2 >= XML_REGEXP_PUNCT) &&
2148 (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2149 ((type2 >= XML_REGEXP_SEPAR) &&
2150 (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2151 ((type2 >= XML_REGEXP_SYMBOL) &&
2152 (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2153 ((type2 >= XML_REGEXP_OTHER) &&
2154 (type2 <= XML_REGEXP_OTHER_NA))
2157 case XML_REGEXP_NOTNAMECHAR: /* \C */
2159 case XML_REGEXP_DECIMAL: /* \d */
2160 /* can't be a letter, mark, separator, pontuation, symbol or other */
2161 if ((type2 == XML_REGEXP_NOTDECIMAL) ||
2162 (type2 == XML_REGEXP_REALCHAR) ||
2163 ((type2 >= XML_REGEXP_LETTER) &&
2164 (type2 <= XML_REGEXP_LETTER_OTHERS)) ||
2165 ((type2 >= XML_REGEXP_MARK) &&
2166 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2167 ((type2 >= XML_REGEXP_PUNCT) &&
2168 (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2169 ((type2 >= XML_REGEXP_SEPAR) &&
2170 (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2171 ((type2 >= XML_REGEXP_SYMBOL) &&
2172 (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2173 ((type2 >= XML_REGEXP_OTHER) &&
2174 (type2 <= XML_REGEXP_OTHER_NA))
2177 case XML_REGEXP_NOTDECIMAL: /* \D */
2179 case XML_REGEXP_REALCHAR: /* \w */
2180 /* can't be a mark, separator, pontuation, symbol or other */
2181 if ((type2 == XML_REGEXP_NOTDECIMAL) ||
2182 ((type2 >= XML_REGEXP_MARK) &&
2183 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2184 ((type2 >= XML_REGEXP_PUNCT) &&
2185 (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2186 ((type2 >= XML_REGEXP_SEPAR) &&
2187 (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2188 ((type2 >= XML_REGEXP_SYMBOL) &&
2189 (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2190 ((type2 >= XML_REGEXP_OTHER) &&
2191 (type2 <= XML_REGEXP_OTHER_NA))
2194 case XML_REGEXP_NOTREALCHAR: /* \W */
2197 * at that point we know both type 1 and type2 are from
2198 * character categories are ordered and are different,
2199 * it becomes simple because this is a partition
2201 case XML_REGEXP_LETTER:
2202 if (type2 <= XML_REGEXP_LETTER_OTHERS)
2205 case XML_REGEXP_LETTER_UPPERCASE:
2206 case XML_REGEXP_LETTER_LOWERCASE:
2207 case XML_REGEXP_LETTER_TITLECASE:
2208 case XML_REGEXP_LETTER_MODIFIER:
2209 case XML_REGEXP_LETTER_OTHERS:
2211 case XML_REGEXP_MARK:
2212 if (type2 <= XML_REGEXP_MARK_ENCLOSING)
2215 case XML_REGEXP_MARK_NONSPACING:
2216 case XML_REGEXP_MARK_SPACECOMBINING:
2217 case XML_REGEXP_MARK_ENCLOSING:
2219 case XML_REGEXP_NUMBER:
2220 if (type2 <= XML_REGEXP_NUMBER_OTHERS)
2223 case XML_REGEXP_NUMBER_DECIMAL:
2224 case XML_REGEXP_NUMBER_LETTER:
2225 case XML_REGEXP_NUMBER_OTHERS:
2227 case XML_REGEXP_PUNCT:
2228 if (type2 <= XML_REGEXP_PUNCT_OTHERS)
2231 case XML_REGEXP_PUNCT_CONNECTOR:
2232 case XML_REGEXP_PUNCT_DASH:
2233 case XML_REGEXP_PUNCT_OPEN:
2234 case XML_REGEXP_PUNCT_CLOSE:
2235 case XML_REGEXP_PUNCT_INITQUOTE:
2236 case XML_REGEXP_PUNCT_FINQUOTE:
2237 case XML_REGEXP_PUNCT_OTHERS:
2239 case XML_REGEXP_SEPAR:
2240 if (type2 <= XML_REGEXP_SEPAR_PARA)
2243 case XML_REGEXP_SEPAR_SPACE:
2244 case XML_REGEXP_SEPAR_LINE:
2245 case XML_REGEXP_SEPAR_PARA:
2247 case XML_REGEXP_SYMBOL:
2248 if (type2 <= XML_REGEXP_SYMBOL_OTHERS)
2251 case XML_REGEXP_SYMBOL_MATH:
2252 case XML_REGEXP_SYMBOL_CURRENCY:
2253 case XML_REGEXP_SYMBOL_MODIFIER:
2254 case XML_REGEXP_SYMBOL_OTHERS:
2256 case XML_REGEXP_OTHER:
2257 if (type2 <= XML_REGEXP_OTHER_NA)
2260 case XML_REGEXP_OTHER_CONTROL:
2261 case XML_REGEXP_OTHER_FORMAT:
2262 case XML_REGEXP_OTHER_PRIVATE:
2263 case XML_REGEXP_OTHER_NA:
2276 * Compares two atoms to check whether they are the same exactly
2277 * this is used to remove equivalent transitions
2279 * Returns 1 if same and 0 otherwise
2282 xmlFAEqualAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2) {
2287 if ((atom1 == NULL) || (atom2 == NULL))
2290 if (atom1->type != atom2->type)
2292 switch (atom1->type) {
2293 case XML_REGEXP_EPSILON:
2296 case XML_REGEXP_STRING:
2297 ret = xmlStrEqual((xmlChar *)atom1->valuep,
2298 (xmlChar *)atom2->valuep);
2300 case XML_REGEXP_CHARVAL:
2301 ret = (atom1->codepoint == atom2->codepoint);
2303 case XML_REGEXP_RANGES:
2304 /* too hard to do in the general case */
2313 * xmlFACompareAtoms:
2317 * Compares two atoms to check whether they intersect in some ways,
2318 * this is used by xmlFAComputesDeterminism and xmlFARecurseDeterminism only
2320 * Returns 1 if yes and 0 otherwise
2323 xmlFACompareAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2) {
2328 if ((atom1 == NULL) || (atom2 == NULL))
2331 if ((atom1->type == XML_REGEXP_ANYCHAR) ||
2332 (atom2->type == XML_REGEXP_ANYCHAR))
2335 if (atom1->type > atom2->type) {
2341 if (atom1->type != atom2->type) {
2342 ret = xmlFACompareAtomTypes(atom1->type, atom2->type);
2343 /* if they can't intersect at the type level break now */
2347 switch (atom1->type) {
2348 case XML_REGEXP_STRING:
2349 ret = xmlRegStrEqualWildcard((xmlChar *)atom1->valuep,
2350 (xmlChar *)atom2->valuep);
2352 case XML_REGEXP_EPSILON:
2353 goto not_determinist;
2354 case XML_REGEXP_CHARVAL:
2355 if (atom2->type == XML_REGEXP_CHARVAL) {
2356 ret = (atom1->codepoint == atom2->codepoint);
2358 ret = xmlRegCheckCharacter(atom2, atom1->codepoint);
2363 case XML_REGEXP_RANGES:
2364 if (atom2->type == XML_REGEXP_RANGES) {
2366 xmlRegRangePtr r1, r2;
2369 * need to check that none of the ranges eventually matches
2371 for (i = 0;i < atom1->nbRanges;i++) {
2372 for (j = 0;j < atom2->nbRanges;j++) {
2373 r1 = atom1->ranges[i];
2374 r2 = atom2->ranges[j];
2375 res = xmlFACompareRanges(r1, r2);
2386 goto not_determinist;
2389 if (atom1->neg != atom2->neg) {
2399 * xmlFARecurseDeterminism:
2400 * @ctxt: a regexp parser context
2402 * Check whether the associated regexp is determinist,
2403 * should be called after xmlFAEliminateEpsilonTransitions()
2407 xmlFARecurseDeterminism(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state,
2408 int to, xmlRegAtomPtr atom) {
2411 int transnr, nbTrans;
2417 * don't recurse on transitions potentially added in the course of
2420 nbTrans = state->nbTrans;
2421 for (transnr = 0;transnr < nbTrans;transnr++) {
2422 t1 = &(state->trans[transnr]);
2424 * check transitions conflicting with the one looked at
2426 if (t1->atom == NULL) {
2429 res = xmlFARecurseDeterminism(ctxt, ctxt->states[t1->to],
2439 if (xmlFACompareAtoms(t1->atom, atom)) {
2441 /* mark the transition as non-deterministic */
2449 * xmlFAComputesDeterminism:
2450 * @ctxt: a regexp parser context
2452 * Check whether the associated regexp is determinist,
2453 * should be called after xmlFAEliminateEpsilonTransitions()
2457 xmlFAComputesDeterminism(xmlRegParserCtxtPtr ctxt) {
2458 int statenr, transnr;
2459 xmlRegStatePtr state;
2460 xmlRegTransPtr t1, t2, last;
2464 #ifdef DEBUG_REGEXP_GRAPH
2465 printf("xmlFAComputesDeterminism\n");
2466 xmlRegPrintCtxt(stdout, ctxt);
2468 if (ctxt->determinist != -1)
2469 return(ctxt->determinist);
2472 * First cleanup the automata removing cancelled transitions
2474 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2475 state = ctxt->states[statenr];
2478 if (state->nbTrans < 2)
2480 for (transnr = 0;transnr < state->nbTrans;transnr++) {
2481 t1 = &(state->trans[transnr]);
2483 * Determinism checks in case of counted or all transitions
2484 * will have to be handled separately
2486 if (t1->atom == NULL) {
2490 if (t1->to == -1) /* eliminated */
2492 for (i = 0;i < transnr;i++) {
2493 t2 = &(state->trans[i]);
2494 if (t2->to == -1) /* eliminated */
2496 if (t2->atom != NULL) {
2497 if (t1->to == t2->to) {
2498 if (xmlFAEqualAtoms(t1->atom, t2->atom))
2499 t2->to = -1; /* eliminated */
2507 * Check for all states that there aren't 2 transitions
2508 * with the same atom and a different target.
2510 for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2511 state = ctxt->states[statenr];
2514 if (state->nbTrans < 2)
2517 for (transnr = 0;transnr < state->nbTrans;transnr++) {
2518 t1 = &(state->trans[transnr]);
2520 * Determinism checks in case of counted or all transitions
2521 * will have to be handled separately
2523 if (t1->atom == NULL) {
2526 if (t1->to == -1) /* eliminated */
2528 for (i = 0;i < transnr;i++) {
2529 t2 = &(state->trans[i]);
2530 if (t2->to == -1) /* eliminated */
2532 if (t2->atom != NULL) {
2533 /* not determinist ! */
2534 if (xmlFACompareAtoms(t1->atom, t2->atom)) {
2536 /* mark the transitions as non-deterministic ones */
2541 } else if (t1->to != -1) {
2543 * do the closure in case of remaining specific
2544 * epsilon transitions like choices or all
2546 ret = xmlFARecurseDeterminism(ctxt, ctxt->states[t1->to],
2548 /* don't shortcut the computation so all non deterministic
2549 transition get marked down
2560 /* don't shortcut the computation so all non deterministic
2561 transition get marked down
2567 * mark specifically the last non-deterministic transition
2568 * from a state since there is no need to set-up rollback
2575 /* don't shortcut the computation so all non deterministic
2576 transition get marked down
2581 ctxt->determinist = ret;
2585 /************************************************************************
2587 * Routines to check input against transition atoms *
2589 ************************************************************************/
2592 xmlRegCheckCharacterRange(xmlRegAtomType type, int codepoint, int neg,
2593 int start, int end, const xmlChar *blockName) {
2597 case XML_REGEXP_STRING:
2598 case XML_REGEXP_SUBREG:
2599 case XML_REGEXP_RANGES:
2600 case XML_REGEXP_EPSILON:
2602 case XML_REGEXP_ANYCHAR:
2603 ret = ((codepoint != '\n') && (codepoint != '\r'));
2605 case XML_REGEXP_CHARVAL:
2606 ret = ((codepoint >= start) && (codepoint <= end));
2608 case XML_REGEXP_NOTSPACE:
2610 case XML_REGEXP_ANYSPACE:
2611 ret = ((codepoint == '\n') || (codepoint == '\r') ||
2612 (codepoint == '\t') || (codepoint == ' '));
2614 case XML_REGEXP_NOTINITNAME:
2616 case XML_REGEXP_INITNAME:
2617 ret = (IS_LETTER(codepoint) ||
2618 (codepoint == '_') || (codepoint == ':'));
2620 case XML_REGEXP_NOTNAMECHAR:
2622 case XML_REGEXP_NAMECHAR:
2623 ret = (IS_LETTER(codepoint) || IS_DIGIT(codepoint) ||
2624 (codepoint == '.') || (codepoint == '-') ||
2625 (codepoint == '_') || (codepoint == ':') ||
2626 IS_COMBINING(codepoint) || IS_EXTENDER(codepoint));
2628 case XML_REGEXP_NOTDECIMAL:
2630 case XML_REGEXP_DECIMAL:
2631 ret = xmlUCSIsCatNd(codepoint);
2633 case XML_REGEXP_REALCHAR:
2635 case XML_REGEXP_NOTREALCHAR:
2636 ret = xmlUCSIsCatP(codepoint);
2638 ret = xmlUCSIsCatZ(codepoint);
2640 ret = xmlUCSIsCatC(codepoint);
2642 case XML_REGEXP_LETTER:
2643 ret = xmlUCSIsCatL(codepoint);
2645 case XML_REGEXP_LETTER_UPPERCASE:
2646 ret = xmlUCSIsCatLu(codepoint);
2648 case XML_REGEXP_LETTER_LOWERCASE:
2649 ret = xmlUCSIsCatLl(codepoint);
2651 case XML_REGEXP_LETTER_TITLECASE:
2652 ret = xmlUCSIsCatLt(codepoint);
2654 case XML_REGEXP_LETTER_MODIFIER:
2655 ret = xmlUCSIsCatLm(codepoint);
2657 case XML_REGEXP_LETTER_OTHERS:
2658 ret = xmlUCSIsCatLo(codepoint);
2660 case XML_REGEXP_MARK:
2661 ret = xmlUCSIsCatM(codepoint);
2663 case XML_REGEXP_MARK_NONSPACING:
2664 ret = xmlUCSIsCatMn(codepoint);
2666 case XML_REGEXP_MARK_SPACECOMBINING:
2667 ret = xmlUCSIsCatMc(codepoint);
2669 case XML_REGEXP_MARK_ENCLOSING:
2670 ret = xmlUCSIsCatMe(codepoint);
2672 case XML_REGEXP_NUMBER:
2673 ret = xmlUCSIsCatN(codepoint);
2675 case XML_REGEXP_NUMBER_DECIMAL:
2676 ret = xmlUCSIsCatNd(codepoint);
2678 case XML_REGEXP_NUMBER_LETTER:
2679 ret = xmlUCSIsCatNl(codepoint);
2681 case XML_REGEXP_NUMBER_OTHERS:
2682 ret = xmlUCSIsCatNo(codepoint);
2684 case XML_REGEXP_PUNCT:
2685 ret = xmlUCSIsCatP(codepoint);
2687 case XML_REGEXP_PUNCT_CONNECTOR:
2688 ret = xmlUCSIsCatPc(codepoint);
2690 case XML_REGEXP_PUNCT_DASH:
2691 ret = xmlUCSIsCatPd(codepoint);
2693 case XML_REGEXP_PUNCT_OPEN:
2694 ret = xmlUCSIsCatPs(codepoint);
2696 case XML_REGEXP_PUNCT_CLOSE:
2697 ret = xmlUCSIsCatPe(codepoint);
2699 case XML_REGEXP_PUNCT_INITQUOTE:
2700 ret = xmlUCSIsCatPi(codepoint);
2702 case XML_REGEXP_PUNCT_FINQUOTE:
2703 ret = xmlUCSIsCatPf(codepoint);
2705 case XML_REGEXP_PUNCT_OTHERS:
2706 ret = xmlUCSIsCatPo(codepoint);
2708 case XML_REGEXP_SEPAR:
2709 ret = xmlUCSIsCatZ(codepoint);
2711 case XML_REGEXP_SEPAR_SPACE:
2712 ret = xmlUCSIsCatZs(codepoint);
2714 case XML_REGEXP_SEPAR_LINE:
2715 ret = xmlUCSIsCatZl(codepoint);
2717 case XML_REGEXP_SEPAR_PARA:
2718 ret = xmlUCSIsCatZp(codepoint);
2720 case XML_REGEXP_SYMBOL:
2721 ret = xmlUCSIsCatS(codepoint);
2723 case XML_REGEXP_SYMBOL_MATH:
2724 ret = xmlUCSIsCatSm(codepoint);
2726 case XML_REGEXP_SYMBOL_CURRENCY:
2727 ret = xmlUCSIsCatSc(codepoint);
2729 case XML_REGEXP_SYMBOL_MODIFIER:
2730 ret = xmlUCSIsCatSk(codepoint);
2732 case XML_REGEXP_SYMBOL_OTHERS:
2733 ret = xmlUCSIsCatSo(codepoint);
2735 case XML_REGEXP_OTHER:
2736 ret = xmlUCSIsCatC(codepoint);
2738 case XML_REGEXP_OTHER_CONTROL:
2739 ret = xmlUCSIsCatCc(codepoint);
2741 case XML_REGEXP_OTHER_FORMAT:
2742 ret = xmlUCSIsCatCf(codepoint);
2744 case XML_REGEXP_OTHER_PRIVATE:
2745 ret = xmlUCSIsCatCo(codepoint);
2747 case XML_REGEXP_OTHER_NA:
2748 /* ret = xmlUCSIsCatCn(codepoint); */
2749 /* Seems it doesn't exist anymore in recent Unicode releases */
2752 case XML_REGEXP_BLOCK_NAME:
2753 ret = xmlUCSIsBlock(codepoint, (const char *) blockName);
2762 xmlRegCheckCharacter(xmlRegAtomPtr atom, int codepoint) {
2764 xmlRegRangePtr range;
2766 if ((atom == NULL) || (!IS_CHAR(codepoint)))
2769 switch (atom->type) {
2770 case XML_REGEXP_SUBREG:
2771 case XML_REGEXP_EPSILON:
2773 case XML_REGEXP_CHARVAL:
2774 return(codepoint == atom->codepoint);
2775 case XML_REGEXP_RANGES: {
2778 for (i = 0;i < atom->nbRanges;i++) {
2779 range = atom->ranges[i];
2780 if (range->neg == 2) {
2781 ret = xmlRegCheckCharacterRange(range->type, codepoint,
2782 0, range->start, range->end,
2785 return(0); /* excluded char */
2786 } else if (range->neg) {
2787 ret = xmlRegCheckCharacterRange(range->type, codepoint,
2788 0, range->start, range->end,
2795 ret = xmlRegCheckCharacterRange(range->type, codepoint,
2796 0, range->start, range->end,
2799 accept = 1; /* might still be excluded */
2804 case XML_REGEXP_STRING:
2805 printf("TODO: XML_REGEXP_STRING\n");
2807 case XML_REGEXP_ANYCHAR:
2808 case XML_REGEXP_ANYSPACE:
2809 case XML_REGEXP_NOTSPACE:
2810 case XML_REGEXP_INITNAME:
2811 case XML_REGEXP_NOTINITNAME:
2812 case XML_REGEXP_NAMECHAR:
2813 case XML_REGEXP_NOTNAMECHAR:
2814 case XML_REGEXP_DECIMAL:
2815 case XML_REGEXP_NOTDECIMAL:
2816 case XML_REGEXP_REALCHAR:
2817 case XML_REGEXP_NOTREALCHAR:
2818 case XML_REGEXP_LETTER:
2819 case XML_REGEXP_LETTER_UPPERCASE:
2820 case XML_REGEXP_LETTER_LOWERCASE:
2821 case XML_REGEXP_LETTER_TITLECASE:
2822 case XML_REGEXP_LETTER_MODIFIER:
2823 case XML_REGEXP_LETTER_OTHERS:
2824 case XML_REGEXP_MARK:
2825 case XML_REGEXP_MARK_NONSPACING:
2826 case XML_REGEXP_MARK_SPACECOMBINING:
2827 case XML_REGEXP_MARK_ENCLOSING:
2828 case XML_REGEXP_NUMBER:
2829 case XML_REGEXP_NUMBER_DECIMAL:
2830 case XML_REGEXP_NUMBER_LETTER:
2831 case XML_REGEXP_NUMBER_OTHERS:
2832 case XML_REGEXP_PUNCT:
2833 case XML_REGEXP_PUNCT_CONNECTOR:
2834 case XML_REGEXP_PUNCT_DASH:
2835 case XML_REGEXP_PUNCT_OPEN:
2836 case XML_REGEXP_PUNCT_CLOSE:
2837 case XML_REGEXP_PUNCT_INITQUOTE:
2838 case XML_REGEXP_PUNCT_FINQUOTE:
2839 case XML_REGEXP_PUNCT_OTHERS:
2840 case XML_REGEXP_SEPAR:
2841 case XML_REGEXP_SEPAR_SPACE:
2842 case XML_REGEXP_SEPAR_LINE:
2843 case XML_REGEXP_SEPAR_PARA:
2844 case XML_REGEXP_SYMBOL:
2845 case XML_REGEXP_SYMBOL_MATH:
2846 case XML_REGEXP_SYMBOL_CURRENCY:
2847 case XML_REGEXP_SYMBOL_MODIFIER:
2848 case XML_REGEXP_SYMBOL_OTHERS:
2849 case XML_REGEXP_OTHER:
2850 case XML_REGEXP_OTHER_CONTROL:
2851 case XML_REGEXP_OTHER_FORMAT:
2852 case XML_REGEXP_OTHER_PRIVATE:
2853 case XML_REGEXP_OTHER_NA:
2854 case XML_REGEXP_BLOCK_NAME:
2855 ret = xmlRegCheckCharacterRange(atom->type, codepoint, 0, 0, 0,
2856 (const xmlChar *)atom->valuep);
2864 /************************************************************************
2866 * Saving and restoring state of an execution context *
2868 ************************************************************************/
2870 #ifdef DEBUG_REGEXP_EXEC
2872 xmlFARegDebugExec(xmlRegExecCtxtPtr exec) {
2873 printf("state: %d:%d:idx %d", exec->state->no, exec->transno, exec->index);
2874 if (exec->inputStack != NULL) {
2877 for (i = 0;(i < 3) && (i < exec->inputStackNr);i++)
2878 printf("%s ", exec->inputStack[exec->inputStackNr - (i + 1)]);
2880 printf(": %s", &(exec->inputString[exec->index]));
2887 xmlFARegExecSave(xmlRegExecCtxtPtr exec) {
2888 #ifdef DEBUG_REGEXP_EXEC
2891 xmlFARegDebugExec(exec);
2895 if (exec->nbPush > MAX_PUSH) {
2901 if (exec->maxRollbacks == 0) {
2902 exec->maxRollbacks = 4;
2903 exec->rollbacks = (xmlRegExecRollback *) xmlMalloc(exec->maxRollbacks *
2904 sizeof(xmlRegExecRollback));
2905 if (exec->rollbacks == NULL) {
2906 xmlRegexpErrMemory(NULL, "saving regexp");
2907 exec->maxRollbacks = 0;
2910 memset(exec->rollbacks, 0,
2911 exec->maxRollbacks * sizeof(xmlRegExecRollback));
2912 } else if (exec->nbRollbacks >= exec->maxRollbacks) {
2913 xmlRegExecRollback *tmp;
2914 int len = exec->maxRollbacks;
2916 exec->maxRollbacks *= 2;
2917 tmp = (xmlRegExecRollback *) xmlRealloc(exec->rollbacks,
2918 exec->maxRollbacks * sizeof(xmlRegExecRollback));
2920 xmlRegexpErrMemory(NULL, "saving regexp");
2921 exec->maxRollbacks /= 2;
2924 exec->rollbacks = tmp;
2925 tmp = &exec->rollbacks[len];
2926 memset(tmp, 0, (exec->maxRollbacks - len) * sizeof(xmlRegExecRollback));
2928 exec->rollbacks[exec->nbRollbacks].state = exec->state;
2929 exec->rollbacks[exec->nbRollbacks].index = exec->index;
2930 exec->rollbacks[exec->nbRollbacks].nextbranch = exec->transno + 1;
2931 if (exec->comp->nbCounters > 0) {
2932 if (exec->rollbacks[exec->nbRollbacks].counts == NULL) {
2933 exec->rollbacks[exec->nbRollbacks].counts = (int *)
2934 xmlMalloc(exec->comp->nbCounters * sizeof(int));
2935 if (exec->rollbacks[exec->nbRollbacks].counts == NULL) {
2936 xmlRegexpErrMemory(NULL, "saving regexp");
2941 memcpy(exec->rollbacks[exec->nbRollbacks].counts, exec->counts,
2942 exec->comp->nbCounters * sizeof(int));
2944 exec->nbRollbacks++;
2948 xmlFARegExecRollBack(xmlRegExecCtxtPtr exec) {
2949 if (exec->nbRollbacks <= 0) {
2951 #ifdef DEBUG_REGEXP_EXEC
2952 printf("rollback failed on empty stack\n");
2956 exec->nbRollbacks--;
2957 exec->state = exec->rollbacks[exec->nbRollbacks].state;
2958 exec->index = exec->rollbacks[exec->nbRollbacks].index;
2959 exec->transno = exec->rollbacks[exec->nbRollbacks].nextbranch;
2960 if (exec->comp->nbCounters > 0) {
2961 if (exec->rollbacks[exec->nbRollbacks].counts == NULL) {
2962 fprintf(stderr, "exec save: allocation failed");
2966 memcpy(exec->counts, exec->rollbacks[exec->nbRollbacks].counts,
2967 exec->comp->nbCounters * sizeof(int));
2970 #ifdef DEBUG_REGEXP_EXEC
2971 printf("restored ");
2972 xmlFARegDebugExec(exec);
2976 /************************************************************************
2978 * Verifier, running an input against a compiled regexp *
2980 ************************************************************************/
2983 xmlFARegExec(xmlRegexpPtr comp, const xmlChar *content) {
2984 xmlRegExecCtxt execval;
2985 xmlRegExecCtxtPtr exec = &execval;
2986 int ret, codepoint = 0, len, deter;
2988 exec->inputString = content;
2991 exec->determinist = 1;
2992 exec->maxRollbacks = 0;
2993 exec->nbRollbacks = 0;
2994 exec->rollbacks = NULL;
2997 exec->state = comp->states[0];
2999 exec->transcount = 0;
3000 exec->inputStack = NULL;
3001 exec->inputStackMax = 0;
3002 if (comp->nbCounters > 0) {
3003 exec->counts = (int *) xmlMalloc(comp->nbCounters * sizeof(int));
3004 if (exec->counts == NULL) {
3005 xmlRegexpErrMemory(NULL, "running regexp");
3008 memset(exec->counts, 0, comp->nbCounters * sizeof(int));
3010 exec->counts = NULL;
3011 while ((exec->status == 0) &&
3012 ((exec->inputString[exec->index] != 0) ||
3013 (exec->state->type != XML_REGEXP_FINAL_STATE))) {
3014 xmlRegTransPtr trans;
3018 * If end of input on non-terminal state, rollback, however we may
3019 * still have epsilon like transition for counted transitions
3020 * on counters, in that case don't break too early. Additionally,
3021 * if we are working on a range like "AB{0,2}", where B is not present,
3022 * we don't want to break.
3025 if ((exec->inputString[exec->index] == 0) && (exec->counts == NULL)) {
3027 * if there is a transition, we must check if
3028 * atom allows minOccurs of 0
3030 if (exec->transno < exec->state->nbTrans) {
3031 trans = &exec->state->trans[exec->transno];
3032 if (trans->to >=0) {
3034 if (!((atom->min == 0) && (atom->max > 0)))
3041 exec->transcount = 0;
3042 for (;exec->transno < exec->state->nbTrans;exec->transno++) {
3043 trans = &exec->state->trans[exec->transno];
3049 if (trans->count >= 0) {
3051 xmlRegCounterPtr counter;
3053 if (exec->counts == NULL) {
3058 * A counted transition.
3061 count = exec->counts[trans->count];
3062 counter = &exec->comp->counters[trans->count];
3063 #ifdef DEBUG_REGEXP_EXEC
3064 printf("testing count %d: val %d, min %d, max %d\n",
3065 trans->count, count, counter->min, counter->max);
3067 ret = ((count >= counter->min) && (count <= counter->max));
3068 if ((ret) && (counter->min != counter->max))
3070 } else if (atom == NULL) {
3071 fprintf(stderr, "epsilon transition left at runtime\n");
3074 } else if (exec->inputString[exec->index] != 0) {
3075 codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len);
3076 ret = xmlRegCheckCharacter(atom, codepoint);
3077 if ((ret == 1) && (atom->min >= 0) && (atom->max > 0)) {
3078 xmlRegStatePtr to = comp->states[trans->to];
3081 * this is a multiple input sequence
3082 * If there is a counter associated increment it now.
3083 * before potentially saving and rollback
3085 if (trans->counter >= 0) {
3086 if (exec->counts == NULL) {
3090 #ifdef DEBUG_REGEXP_EXEC
3091 printf("Increasing count %d\n", trans->counter);
3093 exec->counts[trans->counter]++;
3095 if (exec->state->nbTrans > exec->transno + 1) {
3096 xmlFARegExecSave(exec);
3098 exec->transcount = 1;
3101 * Try to progress as much as possible on the input
3103 if (exec->transcount == atom->max) {
3108 * End of input: stop here
3110 if (exec->inputString[exec->index] == 0) {
3114 if (exec->transcount >= atom->min) {
3115 int transno = exec->transno;
3116 xmlRegStatePtr state = exec->state;
3119 * The transition is acceptable save it
3121 exec->transno = -1; /* trick */
3123 xmlFARegExecSave(exec);
3124 exec->transno = transno;
3125 exec->state = state;
3127 codepoint = CUR_SCHAR(&(exec->inputString[exec->index]),
3129 ret = xmlRegCheckCharacter(atom, codepoint);
3132 if (exec->transcount < atom->min)
3136 * If the last check failed but one transition was found
3137 * possible, rollback
3144 if (trans->counter >= 0) {
3145 if (exec->counts == NULL) {
3149 #ifdef DEBUG_REGEXP_EXEC
3150 printf("Decreasing count %d\n", trans->counter);
3152 exec->counts[trans->counter]--;
3154 } else if ((ret == 0) && (atom->min == 0) && (atom->max > 0)) {
3156 * we don't match on the codepoint, but minOccurs of 0
3157 * says that's ok. Setting len to 0 inhibits stepping
3158 * over the codepoint.
3160 exec->transcount = 1;
3164 } else if ((atom->min == 0) && (atom->max > 0)) {
3165 /* another spot to match when minOccurs is 0 */
3166 exec->transcount = 1;
3171 if ((trans->nd == 1) ||
3172 ((trans->count >= 0) && (deter == 0) &&
3173 (exec->state->nbTrans > exec->transno + 1))) {
3174 #ifdef DEBUG_REGEXP_EXEC
3176 printf("Saving on nd transition atom %d for %c at %d\n",
3177 trans->atom->no, codepoint, exec->index);
3179 printf("Saving on counted transition count %d for %c at %d\n",
3180 trans->count, codepoint, exec->index);
3182 xmlFARegExecSave(exec);
3184 if (trans->counter >= 0) {
3185 if (exec->counts == NULL) {
3189 #ifdef DEBUG_REGEXP_EXEC
3190 printf("Increasing count %d\n", trans->counter);
3192 exec->counts[trans->counter]++;
3194 if ((trans->count >= 0) &&
3195 (trans->count < REGEXP_ALL_COUNTER)) {
3196 if (exec->counts == NULL) {
3200 #ifdef DEBUG_REGEXP_EXEC
3201 printf("resetting count %d on transition\n",
3204 exec->counts[trans->count] = 0;
3206 #ifdef DEBUG_REGEXP_EXEC
3207 printf("entering state %d\n", trans->to);
3209 exec->state = comp->states[trans->to];
3211 if (trans->atom != NULL) {
3215 } else if (ret < 0) {
3220 if ((exec->transno != 0) || (exec->state->nbTrans == 0)) {
3223 * Failed to find a way out
3225 exec->determinist = 0;
3226 #ifdef DEBUG_REGEXP_EXEC
3227 printf("rollback from state %d on %d:%c\n", exec->state->no,
3228 codepoint,codepoint);
3230 xmlFARegExecRollBack(exec);
3236 if (exec->rollbacks != NULL) {
3237 if (exec->counts != NULL) {
3240 for (i = 0;i < exec->maxRollbacks;i++)
3241 if (exec->rollbacks[i].counts != NULL)
3242 xmlFree(exec->rollbacks[i].counts);
3244 xmlFree(exec->rollbacks);
3246 if (exec->counts != NULL)
3247 xmlFree(exec->counts);
3248 if (exec->status == 0)
3250 if (exec->status == -1) {
3251 if (exec->nbPush > MAX_PUSH)
3255 return(exec->status);
3258 /************************************************************************
3260 * Progressive interface to the verifier one atom at a time *
3262 ************************************************************************/
3264 static void testerr(xmlRegExecCtxtPtr exec);
3268 * xmlRegNewExecCtxt:
3269 * @comp: a precompiled regular expression
3270 * @callback: a callback function used for handling progresses in the
3271 * automata matching phase
3272 * @data: the context data associated to the callback in this context
3274 * Build a context used for progressive evaluation of a regexp.
3276 * Returns the new context
3279 xmlRegNewExecCtxt(xmlRegexpPtr comp, xmlRegExecCallbacks callback, void *data) {
3280 xmlRegExecCtxtPtr exec;
3284 if ((comp->compact == NULL) && (comp->states == NULL))
3286 exec = (xmlRegExecCtxtPtr) xmlMalloc(sizeof(xmlRegExecCtxt));
3288 xmlRegexpErrMemory(NULL, "creating execution context");
3291 memset(exec, 0, sizeof(xmlRegExecCtxt));
3292 exec->inputString = NULL;
3294 exec->determinist = 1;
3295 exec->maxRollbacks = 0;
3296 exec->nbRollbacks = 0;
3297 exec->rollbacks = NULL;
3300 if (comp->compact == NULL)
3301 exec->state = comp->states[0];
3303 exec->transcount = 0;
3304 exec->callback = callback;
3306 if (comp->nbCounters > 0) {
3308 * For error handling, exec->counts is allocated twice the size
3309 * the second half is used to store the data in case of rollback
3311 exec->counts = (int *) xmlMalloc(comp->nbCounters * sizeof(int)
3313 if (exec->counts == NULL) {
3314 xmlRegexpErrMemory(NULL, "creating execution context");
3318 memset(exec->counts, 0, comp->nbCounters * sizeof(int) * 2);
3319 exec->errCounts = &exec->counts[comp->nbCounters];
3321 exec->counts = NULL;
3322 exec->errCounts = NULL;
3324 exec->inputStackMax = 0;
3325 exec->inputStackNr = 0;
3326 exec->inputStack = NULL;
3327 exec->errStateNo = -1;
3328 exec->errString = NULL;
3334 * xmlRegFreeExecCtxt:
3335 * @exec: a regular expression evaulation context
3337 * Free the structures associated to a regular expression evaulation context.
3340 xmlRegFreeExecCtxt(xmlRegExecCtxtPtr exec) {
3344 if (exec->rollbacks != NULL) {
3345 if (exec->counts != NULL) {
3348 for (i = 0;i < exec->maxRollbacks;i++)
3349 if (exec->rollbacks[i].counts != NULL)
3350 xmlFree(exec->rollbacks[i].counts);
3352 xmlFree(exec->rollbacks);
3354 if (exec->counts != NULL)
3355 xmlFree(exec->counts);
3356 if (exec->inputStack != NULL) {
3359 for (i = 0;i < exec->inputStackNr;i++) {
3360 if (exec->inputStack[i].value != NULL)
3361 xmlFree(exec->inputStack[i].value);
3363 xmlFree(exec->inputStack);
3365 if (exec->errString != NULL)
3366 xmlFree(exec->errString);
3371 xmlFARegExecSaveInputString(xmlRegExecCtxtPtr exec, const xmlChar *value,
3374 printf("saving value: %d:%s\n", exec->inputStackNr, value);
3376 if (exec->inputStackMax == 0) {
3377 exec->inputStackMax = 4;
3378 exec->inputStack = (xmlRegInputTokenPtr)
3379 xmlMalloc(exec->inputStackMax * sizeof(xmlRegInputToken));
3380 if (exec->inputStack == NULL) {
3381 xmlRegexpErrMemory(NULL, "pushing input string");
3382 exec->inputStackMax = 0;
3385 } else if (exec->inputStackNr + 1 >= exec->inputStackMax) {
3386 xmlRegInputTokenPtr tmp;
3388 exec->inputStackMax *= 2;
3389 tmp = (xmlRegInputTokenPtr) xmlRealloc(exec->inputStack,
3390 exec->inputStackMax * sizeof(xmlRegInputToken));
3392 xmlRegexpErrMemory(NULL, "pushing input string");
3393 exec->inputStackMax /= 2;
3396 exec->inputStack = tmp;
3398 exec->inputStack[exec->inputStackNr].value = xmlStrdup(value);
3399 exec->inputStack[exec->inputStackNr].data = data;
3400 exec->inputStackNr++;
3401 exec->inputStack[exec->inputStackNr].value = NULL;
3402 exec->inputStack[exec->inputStackNr].data = NULL;
3406 * xmlRegStrEqualWildcard:
3407 * @expStr: the string to be evaluated
3408 * @valStr: the validation string
3410 * Checks if both strings are equal or have the same content. "*"
3411 * can be used as a wildcard in @valStr; "|" is used as a seperator of
3412 * substrings in both @expStr and @valStr.
3414 * Returns 1 if the comparison is satisfied and the number of substrings
3415 * is equal, 0 otherwise.
3419 xmlRegStrEqualWildcard(const xmlChar *expStr, const xmlChar *valStr) {
3420 if (expStr == valStr) return(1);
3421 if (expStr == NULL) return(0);
3422 if (valStr == NULL) return(0);
3425 * Eval if we have a wildcard for the current item.
3427 if (*expStr != *valStr) {
3428 /* if one of them starts with a wildcard make valStr be it */
3429 if (*valStr == '*') {
3436 if ((*valStr != 0) && (*expStr != 0) && (*expStr++ == '*')) {
3438 if (*valStr == XML_REG_STRING_SEPARATOR)
3441 } while (*valStr != 0);
3448 } while (*valStr != 0);
3456 * xmlRegCompactPushString:
3457 * @exec: a regexp execution context
3458 * @comp: the precompiled exec with a compact table
3459 * @value: a string token input
3460 * @data: data associated to the token to reuse in callbacks
3462 * Push one input token in the execution context
3464 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
3465 * a negative value in case of error.
3468 xmlRegCompactPushString(xmlRegExecCtxtPtr exec,
3470 const xmlChar *value,
3472 int state = exec->index;
3475 if ((comp == NULL) || (comp->compact == NULL) || (comp->stringMap == NULL))
3478 if (value == NULL) {
3480 * are we at a final state ?
3482 if (comp->compact[state * (comp->nbstrings + 1)] ==
3483 XML_REGEXP_FINAL_STATE)
3489 printf("value pushed: %s\n", value);
3493 * Examine all outside transitions from current state
3495 for (i = 0;i < comp->nbstrings;i++) {
3496 target = comp->compact[state * (comp->nbstrings + 1) + i + 1];
3497 if ((target > 0) && (target <= comp->nbstates)) {
3498 target--; /* to avoid 0 */
3499 if (xmlRegStrEqualWildcard(comp->stringMap[i], value)) {
3500 exec->index = target;
3501 if ((exec->callback != NULL) && (comp->transdata != NULL)) {
3502 exec->callback(exec->data, value,
3503 comp->transdata[state * comp->nbstrings + i], data);
3506 printf("entering state %d\n", target);
3508 if (comp->compact[target * (comp->nbstrings + 1)] ==
3509 XML_REGEXP_SINK_STATE)
3512 if (comp->compact[target * (comp->nbstrings + 1)] ==
3513 XML_REGEXP_FINAL_STATE)
3520 * Failed to find an exit transition out from current state for the
3524 printf("failed to find a transition for %s on state %d\n", value, state);
3527 if (exec->errString != NULL)
3528 xmlFree(exec->errString);
3529 exec->errString = xmlStrdup(value);
3530 exec->errStateNo = state;
3539 * xmlRegExecPushStringInternal:
3540 * @exec: a regexp execution context or NULL to indicate the end
3541 * @value: a string token input
3542 * @data: data associated to the token to reuse in callbacks
3543 * @compound: value was assembled from 2 strings
3545 * Push one input token in the execution context
3547 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
3548 * a negative value in case of error.
3551 xmlRegExecPushStringInternal(xmlRegExecCtxtPtr exec, const xmlChar *value,
3552 void *data, int compound) {
3553 xmlRegTransPtr trans;
3561 if (exec->comp == NULL)
3563 if (exec->status != 0)
3564 return(exec->status);
3566 if (exec->comp->compact != NULL)
3567 return(xmlRegCompactPushString(exec, exec->comp, value, data));
3569 if (value == NULL) {
3570 if (exec->state->type == XML_REGEXP_FINAL_STATE)
3576 printf("value pushed: %s\n", value);
3579 * If we have an active rollback stack push the new value there
3580 * and get back to where we were left
3582 if ((value != NULL) && (exec->inputStackNr > 0)) {
3583 xmlFARegExecSaveInputString(exec, value, data);
3584 value = exec->inputStack[exec->index].value;
3585 data = exec->inputStack[exec->index].data;
3587 printf("value loaded: %s\n", value);
3591 while ((exec->status == 0) &&
3594 (exec->state->type != XML_REGEXP_FINAL_STATE)))) {
3597 * End of input on non-terminal state, rollback, however we may
3598 * still have epsilon like transition for counted transitions
3599 * on counters, in that case don't break too early.
3601 if ((value == NULL) && (exec->counts == NULL))
3604 exec->transcount = 0;
3605 for (;exec->transno < exec->state->nbTrans;exec->transno++) {
3606 trans = &exec->state->trans[exec->transno];
3611 if (trans->count == REGEXP_ALL_LAX_COUNTER) {
3615 xmlRegCounterPtr counter;
3620 printf("testing all lax %d\n", trans->count);
3623 * Check all counted transitions from the current state
3625 if ((value == NULL) && (final)) {
3627 } else if (value != NULL) {
3628 for (i = 0;i < exec->state->nbTrans;i++) {
3629 t = &exec->state->trans[i];
3630 if ((t->counter < 0) || (t == trans))
3632 counter = &exec->comp->counters[t->counter];
3633 count = exec->counts[t->counter];
3634 if ((count < counter->max) &&
3635 (t->atom != NULL) &&
3636 (xmlStrEqual(value, t->atom->valuep))) {
3640 if ((count >= counter->min) &&
3641 (count < counter->max) &&
3642 (t->atom != NULL) &&
3643 (xmlStrEqual(value, t->atom->valuep))) {
3649 } else if (trans->count == REGEXP_ALL_COUNTER) {
3653 xmlRegCounterPtr counter;
3658 printf("testing all %d\n", trans->count);
3661 * Check all counted transitions from the current state
3663 for (i = 0;i < exec->state->nbTrans;i++) {
3664 t = &exec->state->trans[i];
3665 if ((t->counter < 0) || (t == trans))
3667 counter = &exec->comp->counters[t->counter];
3668 count = exec->counts[t->counter];
3669 if ((count < counter->min) || (count > counter->max)) {
3674 } else if (trans->count >= 0) {
3676 xmlRegCounterPtr counter;
3679 * A counted transition.
3682 count = exec->counts[trans->count];
3683 counter = &exec->comp->counters[trans->count];
3685 printf("testing count %d: val %d, min %d, max %d\n",
3686 trans->count, count, counter->min, counter->max);
3688 ret = ((count >= counter->min) && (count <= counter->max));
3689 } else if (atom == NULL) {
3690 fprintf(stderr, "epsilon transition left at runtime\n");
3693 } else if (value != NULL) {
3694 ret = xmlRegStrEqualWildcard(atom->valuep, value);
3700 if ((ret == 1) && (trans->counter >= 0)) {
3701 xmlRegCounterPtr counter;
3704 count = exec->counts[trans->counter];
3705 counter = &exec->comp->counters[trans->counter];
3706 if (count >= counter->max)
3710 if ((ret == 1) && (atom->min > 0) && (atom->max > 0)) {
3711 xmlRegStatePtr to = exec->comp->states[trans->to];
3714 * this is a multiple input sequence
3716 if (exec->state->nbTrans > exec->transno + 1) {
3717 if (exec->inputStackNr <= 0) {
3718 xmlFARegExecSaveInputString(exec, value, data);
3720 xmlFARegExecSave(exec);
3722 exec->transcount = 1;
3725 * Try to progress as much as possible on the input
3727 if (exec->transcount == atom->max) {
3731 value = exec->inputStack[exec->index].value;
3732 data = exec->inputStack[exec->index].data;
3734 printf("value loaded: %s\n", value);
3738 * End of input: stop here
3740 if (value == NULL) {
3744 if (exec->transcount >= atom->min) {
3745 int transno = exec->transno;
3746 xmlRegStatePtr state = exec->state;
3749 * The transition is acceptable save it
3751 exec->transno = -1; /* trick */
3753 if (exec->inputStackNr <= 0) {
3754 xmlFARegExecSaveInputString(exec, value, data);
3756 xmlFARegExecSave(exec);
3757 exec->transno = transno;
3758 exec->state = state;
3760 ret = xmlStrEqual(value, atom->valuep);
3763 if (exec->transcount < atom->min)
3767 * If the last check failed but one transition was found
3768 * possible, rollback
3778 if ((exec->callback != NULL) && (atom != NULL) &&
3780 exec->callback(exec->data, atom->valuep,
3783 if (exec->state->nbTrans > exec->transno + 1) {
3784 if (exec->inputStackNr <= 0) {
3785 xmlFARegExecSaveInputString(exec, value, data);
3787 xmlFARegExecSave(exec);
3789 if (trans->counter >= 0) {
3791 printf("Increasing count %d\n", trans->counter);
3793 exec->counts[trans->counter]++;
3795 if ((trans->count >= 0) &&
3796 (trans->count < REGEXP_ALL_COUNTER)) {
3797 #ifdef DEBUG_REGEXP_EXEC
3798 printf("resetting count %d on transition\n",
3801 exec->counts[trans->count] = 0;
3804 printf("entering state %d\n", trans->to);
3806 if ((exec->comp->states[trans->to] != NULL) &&
3807 (exec->comp->states[trans->to]->type ==
3808 XML_REGEXP_SINK_STATE)) {
3810 * entering a sink state, save the current state as error
3813 if (exec->errString != NULL)
3814 xmlFree(exec->errString);
3815 exec->errString = xmlStrdup(value);
3816 exec->errState = exec->state;
3817 memcpy(exec->errCounts, exec->counts,
3818 exec->comp->nbCounters * sizeof(int));
3820 exec->state = exec->comp->states[trans->to];
3822 if (trans->atom != NULL) {
3823 if (exec->inputStack != NULL) {
3825 if (exec->index < exec->inputStackNr) {
3826 value = exec->inputStack[exec->index].value;
3827 data = exec->inputStack[exec->index].data;
3829 printf("value loaded: %s\n", value);
3835 printf("end of input\n");
3842 printf("end of input\n");
3847 } else if (ret < 0) {
3852 if ((exec->transno != 0) || (exec->state->nbTrans == 0)) {
3855 * if we didn't yet rollback on the current input
3856 * store the current state as the error state.
3858 if ((progress) && (exec->state != NULL) &&
3859 (exec->state->type != XML_REGEXP_SINK_STATE)) {
3861 if (exec->errString != NULL)
3862 xmlFree(exec->errString);
3863 exec->errString = xmlStrdup(value);
3864 exec->errState = exec->state;
3865 memcpy(exec->errCounts, exec->counts,
3866 exec->comp->nbCounters * sizeof(int));
3870 * Failed to find a way out
3872 exec->determinist = 0;
3873 xmlFARegExecRollBack(exec);
3874 if (exec->status == 0) {
3875 value = exec->inputStack[exec->index].value;
3876 data = exec->inputStack[exec->index].data;
3878 printf("value loaded: %s\n", value);
3887 if (exec->status == 0) {
3888 return(exec->state->type == XML_REGEXP_FINAL_STATE);
3891 if (exec->status < 0) {
3895 return(exec->status);
3899 * xmlRegExecPushString:
3900 * @exec: a regexp execution context or NULL to indicate the end
3901 * @value: a string token input
3902 * @data: data associated to the token to reuse in callbacks
3904 * Push one input token in the execution context
3906 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
3907 * a negative value in case of error.
3910 xmlRegExecPushString(xmlRegExecCtxtPtr exec, const xmlChar *value,
3912 return(xmlRegExecPushStringInternal(exec, value, data, 0));
3916 * xmlRegExecPushString2:
3917 * @exec: a regexp execution context or NULL to indicate the end
3918 * @value: the first string token input
3919 * @value2: the second string token input
3920 * @data: data associated to the token to reuse in callbacks
3922 * Push one input token in the execution context
3924 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
3925 * a negative value in case of error.
3928 xmlRegExecPushString2(xmlRegExecCtxtPtr exec, const xmlChar *value,
3929 const xmlChar *value2, void *data) {
3931 int lenn, lenp, ret;
3936 if (exec->comp == NULL)
3938 if (exec->status != 0)
3939 return(exec->status);
3942 return(xmlRegExecPushString(exec, value, data));
3944 lenn = strlen((char *) value2);
3945 lenp = strlen((char *) value);
3947 if (150 < lenn + lenp + 2) {
3948 str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
3956 memcpy(&str[0], value, lenp);
3957 str[lenp] = XML_REG_STRING_SEPARATOR;
3958 memcpy(&str[lenp + 1], value2, lenn);
3959 str[lenn + lenp + 1] = 0;
3961 if (exec->comp->compact != NULL)
3962 ret = xmlRegCompactPushString(exec, exec->comp, str, data);
3964 ret = xmlRegExecPushStringInternal(exec, str, data, 1);
3972 * xmlRegExecGetValues:
3973 * @exec: a regexp execution context
3974 * @err: error extraction or normal one
3975 * @nbval: pointer to the number of accepted values IN/OUT
3976 * @nbneg: return number of negative transitions
3977 * @values: pointer to the array of acceptable values
3978 * @terminal: return value if this was a terminal state
3980 * Extract informations from the regexp execution, internal routine to
3981 * implement xmlRegExecNextValues() and xmlRegExecErrInfo()
3983 * Returns: 0 in case of success or -1 in case of error.
3986 xmlRegExecGetValues(xmlRegExecCtxtPtr exec, int err,
3987 int *nbval, int *nbneg,
3988 xmlChar **values, int *terminal) {
3992 if ((exec == NULL) || (nbval == NULL) || (nbneg == NULL) ||
3993 (values == NULL) || (*nbval <= 0))
3999 if ((exec->comp != NULL) && (exec->comp->compact != NULL)) {
4001 int target, i, state;
4006 if (exec->errStateNo == -1) return(-1);
4007 state = exec->errStateNo;
4009 state = exec->index;
4011 if (terminal != NULL) {
4012 if (comp->compact[state * (comp->nbstrings + 1)] ==
4013 XML_REGEXP_FINAL_STATE)
4018 for (i = 0;(i < comp->nbstrings) && (nb < maxval);i++) {
4019 target = comp->compact[state * (comp->nbstrings + 1) + i + 1];
4020 if ((target > 0) && (target <= comp->nbstates) &&
4021 (comp->compact[(target - 1) * (comp->nbstrings + 1)] !=
4022 XML_REGEXP_SINK_STATE)) {
4023 values[nb++] = comp->stringMap[i];
4027 for (i = 0;(i < comp->nbstrings) && (nb < maxval);i++) {
4028 target = comp->compact[state * (comp->nbstrings + 1) + i + 1];
4029 if ((target > 0) && (target <= comp->nbstates) &&
4030 (comp->compact[(target - 1) * (comp->nbstrings + 1)] ==
4031 XML_REGEXP_SINK_STATE)) {
4032 values[nb++] = comp->stringMap[i];
4038 xmlRegTransPtr trans;
4040 xmlRegStatePtr state;
4042 if (terminal != NULL) {
4043 if (exec->state->type == XML_REGEXP_FINAL_STATE)
4050 if (exec->errState == NULL) return(-1);
4051 state = exec->errState;
4053 if (exec->state == NULL) return(-1);
4054 state = exec->state;
4057 (transno < state->nbTrans) && (nb < maxval);
4059 trans = &state->trans[transno];
4063 if ((atom == NULL) || (atom->valuep == NULL))
4065 if (trans->count == REGEXP_ALL_LAX_COUNTER) {
4066 /* this should not be reached but ... */
4068 } else if (trans->count == REGEXP_ALL_COUNTER) {
4069 /* this should not be reached but ... */
4071 } else if (trans->counter >= 0) {
4072 xmlRegCounterPtr counter = NULL;
4076 count = exec->errCounts[trans->counter];
4078 count = exec->counts[trans->counter];
4079 if (exec->comp != NULL)
4080 counter = &exec->comp->counters[trans->counter];
4081 if ((counter == NULL) || (count < counter->max)) {
4083 values[nb++] = (xmlChar *) atom->valuep2;
4085 values[nb++] = (xmlChar *) atom->valuep;
4089 if ((exec->comp->states[trans->to] != NULL) &&
4090 (exec->comp->states[trans->to]->type !=
4091 XML_REGEXP_SINK_STATE)) {
4093 values[nb++] = (xmlChar *) atom->valuep2;
4095 values[nb++] = (xmlChar *) atom->valuep;
4101 (transno < state->nbTrans) && (nb < maxval);
4103 trans = &state->trans[transno];
4107 if ((atom == NULL) || (atom->valuep == NULL))
4109 if (trans->count == REGEXP_ALL_LAX_COUNTER) {
4111 } else if (trans->count == REGEXP_ALL_COUNTER) {
4113 } else if (trans->counter >= 0) {
4116 if ((exec->comp->states[trans->to] != NULL) &&
4117 (exec->comp->states[trans->to]->type ==
4118 XML_REGEXP_SINK_STATE)) {
4120 values[nb++] = (xmlChar *) atom->valuep2;
4122 values[nb++] = (xmlChar *) atom->valuep;
4132 * xmlRegExecNextValues:
4133 * @exec: a regexp execution context
4134 * @nbval: pointer to the number of accepted values IN/OUT
4135 * @nbneg: return number of negative transitions
4136 * @values: pointer to the array of acceptable values
4137 * @terminal: return value if this was a terminal state
4139 * Extract informations from the regexp execution,
4140 * the parameter @values must point to an array of @nbval string pointers
4141 * on return nbval will contain the number of possible strings in that
4142 * state and the @values array will be updated with them. The string values
4143 * returned will be freed with the @exec context and don't need to be
4146 * Returns: 0 in case of success or -1 in case of error.
4149 xmlRegExecNextValues(xmlRegExecCtxtPtr exec, int *nbval, int *nbneg,
4150 xmlChar **values, int *terminal) {
4151 return(xmlRegExecGetValues(exec, 0, nbval, nbneg, values, terminal));
4155 * xmlRegExecErrInfo:
4156 * @exec: a regexp execution context generating an error
4157 * @string: return value for the error string
4158 * @nbval: pointer to the number of accepted values IN/OUT
4159 * @nbneg: return number of negative transitions
4160 * @values: pointer to the array of acceptable values
4161 * @terminal: return value if this was a terminal state
4163 * Extract error informations from the regexp execution, the parameter
4164 * @string will be updated with the value pushed and not accepted,
4165 * the parameter @values must point to an array of @nbval string pointers
4166 * on return nbval will contain the number of possible strings in that
4167 * state and the @values array will be updated with them. The string values
4168 * returned will be freed with the @exec context and don't need to be
4171 * Returns: 0 in case of success or -1 in case of error.
4174 xmlRegExecErrInfo(xmlRegExecCtxtPtr exec, const xmlChar **string,
4175 int *nbval, int *nbneg, xmlChar **values, int *terminal) {
4178 if (string != NULL) {
4179 if (exec->status != 0)
4180 *string = exec->errString;
4184 return(xmlRegExecGetValues(exec, 1, nbval, nbneg, values, terminal));
4188 static void testerr(xmlRegExecCtxtPtr exec) {
4189 const xmlChar *string;
4194 xmlRegExecErrInfo(exec, &string, &nb, &nbneg, &values[0], &terminal);
4200 xmlRegExecPushChar(xmlRegExecCtxtPtr exec, int UCS) {
4201 xmlRegTransPtr trans;
4208 if (exec->status != 0)
4209 return(exec->status);
4211 while ((exec->status == 0) &&
4212 ((exec->inputString[exec->index] != 0) ||
4213 (exec->state->type != XML_REGEXP_FINAL_STATE))) {
4216 * End of input on non-terminal state, rollback, however we may
4217 * still have epsilon like transition for counted transitions
4218 * on counters, in that case don't break too early.
4220 if ((exec->inputString[exec->index] == 0) && (exec->counts == NULL))
4223 exec->transcount = 0;
4224 for (;exec->transno < exec->state->nbTrans;exec->transno++) {
4225 trans = &exec->state->trans[exec->transno];
4230 if (trans->count >= 0) {
4232 xmlRegCounterPtr counter;
4235 * A counted transition.
4238 count = exec->counts[trans->count];
4239 counter = &exec->comp->counters[trans->count];
4240 #ifdef DEBUG_REGEXP_EXEC
4241 printf("testing count %d: val %d, min %d, max %d\n",
4242 trans->count, count, counter->min, counter->max);
4244 ret = ((count >= counter->min) && (count <= counter->max));
4245 } else if (atom == NULL) {
4246 fprintf(stderr, "epsilon transition left at runtime\n");
4249 } else if (exec->inputString[exec->index] != 0) {
4250 codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len);
4251 ret = xmlRegCheckCharacter(atom, codepoint);
4252 if ((ret == 1) && (atom->min > 0) && (atom->max > 0)) {
4253 xmlRegStatePtr to = exec->comp->states[trans->to];
4256 * this is a multiple input sequence
4258 if (exec->state->nbTrans > exec->transno + 1) {
4259 xmlFARegExecSave(exec);
4261 exec->transcount = 1;
4264 * Try to progress as much as possible on the input
4266 if (exec->transcount == atom->max) {
4271 * End of input: stop here
4273 if (exec->inputString[exec->index] == 0) {
4277 if (exec->transcount >= atom->min) {
4278 int transno = exec->transno;
4279 xmlRegStatePtr state = exec->state;
4282 * The transition is acceptable save it
4284 exec->transno = -1; /* trick */
4286 xmlFARegExecSave(exec);
4287 exec->transno = transno;
4288 exec->state = state;
4290 codepoint = CUR_SCHAR(&(exec->inputString[exec->index]),
4292 ret = xmlRegCheckCharacter(atom, codepoint);
4295 if (exec->transcount < atom->min)
4299 * If the last check failed but one transition was found
4300 * possible, rollback
4310 if (exec->state->nbTrans > exec->transno + 1) {
4311 xmlFARegExecSave(exec);
4314 * restart count for expressions like this ((abc){2})*
4316 if (trans->count >= 0) {
4317 #ifdef DEBUG_REGEXP_EXEC
4318 printf("Reset count %d\n", trans->count);
4320 exec->counts[trans->count] = 0;
4322 if (trans->counter >= 0) {
4323 #ifdef DEBUG_REGEXP_EXEC
4324 printf("Increasing count %d\n", trans->counter);
4326 exec->counts[trans->counter]++;
4328 #ifdef DEBUG_REGEXP_EXEC
4329 printf("entering state %d\n", trans->to);
4331 exec->state = exec->comp->states[trans->to];
4333 if (trans->atom != NULL) {
4337 } else if (ret < 0) {
4342 if ((exec->transno != 0) || (exec->state->nbTrans == 0)) {
4345 * Failed to find a way out
4347 exec->determinist = 0;
4348 xmlFARegExecRollBack(exec);
4355 /************************************************************************
4357 * Parser for the Schemas Datatype Regular Expressions *
4358 * http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#regexs *
4360 ************************************************************************/
4364 * @ctxt: a regexp parser context
4366 * [10] Char ::= [^.\?*+()|#x5B#x5D]
4369 xmlFAIsChar(xmlRegParserCtxtPtr ctxt) {
4373 cur = CUR_SCHAR(ctxt->cur, len);
4374 if ((cur == '.') || (cur == '\\') || (cur == '?') ||
4375 (cur == '*') || (cur == '+') || (cur == '(') ||
4376 (cur == ')') || (cur == '|') || (cur == 0x5B) ||
4377 (cur == 0x5D) || (cur == 0))
4383 * xmlFAParseCharProp:
4384 * @ctxt: a regexp parser context
4386 * [27] charProp ::= IsCategory | IsBlock
4387 * [28] IsCategory ::= Letters | Marks | Numbers | Punctuation |
4388 * Separators | Symbols | Others
4389 * [29] Letters ::= 'L' [ultmo]?
4390 * [30] Marks ::= 'M' [nce]?
4391 * [31] Numbers ::= 'N' [dlo]?
4392 * [32] Punctuation ::= 'P' [cdseifo]?
4393 * [33] Separators ::= 'Z' [slp]?
4394 * [34] Symbols ::= 'S' [mcko]?
4395 * [35] Others ::= 'C' [cfon]?
4396 * [36] IsBlock ::= 'Is' [a-zA-Z0-9#x2D]+
4399 xmlFAParseCharProp(xmlRegParserCtxtPtr ctxt) {
4401 xmlRegAtomType type = (xmlRegAtomType) 0;
4402 xmlChar *blockName = NULL;
4410 type = XML_REGEXP_LETTER_UPPERCASE;
4411 } else if (cur == 'l') {
4413 type = XML_REGEXP_LETTER_LOWERCASE;
4414 } else if (cur == 't') {
4416 type = XML_REGEXP_LETTER_TITLECASE;
4417 } else if (cur == 'm') {
4419 type = XML_REGEXP_LETTER_MODIFIER;
4420 } else if (cur == 'o') {
4422 type = XML_REGEXP_LETTER_OTHERS;
4424 type = XML_REGEXP_LETTER;
4426 } else if (cur == 'M') {
4432 type = XML_REGEXP_MARK_NONSPACING;
4433 } else if (cur == 'c') {
4435 /* spacing combining */
4436 type = XML_REGEXP_MARK_SPACECOMBINING;
4437 } else if (cur == 'e') {
4440 type = XML_REGEXP_MARK_ENCLOSING;
4443 type = XML_REGEXP_MARK;
4445 } else if (cur == 'N') {
4451 type = XML_REGEXP_NUMBER_DECIMAL;
4452 } else if (cur == 'l') {
4455 type = XML_REGEXP_NUMBER_LETTER;
4456 } else if (cur == 'o') {
4459 type = XML_REGEXP_NUMBER_OTHERS;
4462 type = XML_REGEXP_NUMBER;
4464 } else if (cur == 'P') {
4470 type = XML_REGEXP_PUNCT_CONNECTOR;
4471 } else if (cur == 'd') {
4474 type = XML_REGEXP_PUNCT_DASH;
4475 } else if (cur == 's') {
4478 type = XML_REGEXP_PUNCT_OPEN;
4479 } else if (cur == 'e') {
4482 type = XML_REGEXP_PUNCT_CLOSE;
4483 } else if (cur == 'i') {
4486 type = XML_REGEXP_PUNCT_INITQUOTE;
4487 } else if (cur == 'f') {
4490 type = XML_REGEXP_PUNCT_FINQUOTE;
4491 } else if (cur == 'o') {
4494 type = XML_REGEXP_PUNCT_OTHERS;
4496 /* all punctuation */
4497 type = XML_REGEXP_PUNCT;
4499 } else if (cur == 'Z') {
4505 type = XML_REGEXP_SEPAR_SPACE;
4506 } else if (cur == 'l') {
4509 type = XML_REGEXP_SEPAR_LINE;
4510 } else if (cur == 'p') {
4513 type = XML_REGEXP_SEPAR_PARA;
4515 /* all separators */
4516 type = XML_REGEXP_SEPAR;
4518 } else if (cur == 'S') {
4523 type = XML_REGEXP_SYMBOL_MATH;
4525 } else if (cur == 'c') {
4527 type = XML_REGEXP_SYMBOL_CURRENCY;
4529 } else if (cur == 'k') {
4531 type = XML_REGEXP_SYMBOL_MODIFIER;
4533 } else if (cur == 'o') {
4535 type = XML_REGEXP_SYMBOL_OTHERS;
4539 type = XML_REGEXP_SYMBOL;
4541 } else if (cur == 'C') {
4547 type = XML_REGEXP_OTHER_CONTROL;
4548 } else if (cur == 'f') {
4551 type = XML_REGEXP_OTHER_FORMAT;
4552 } else if (cur == 'o') {
4555 type = XML_REGEXP_OTHER_PRIVATE;
4556 } else if (cur == 'n') {
4559 type = XML_REGEXP_OTHER_NA;
4562 type = XML_REGEXP_OTHER;
4564 } else if (cur == 'I') {
4565 const xmlChar *start;
4569 ERROR("IsXXXX expected");
4575 if (((cur >= 'a') && (cur <= 'z')) ||
4576 ((cur >= 'A') && (cur <= 'Z')) ||
4577 ((cur >= '0') && (cur <= '9')) ||
4581 while (((cur >= 'a') && (cur <= 'z')) ||
4582 ((cur >= 'A') && (cur <= 'Z')) ||
4583 ((cur >= '0') && (cur <= '9')) ||
4589 type = XML_REGEXP_BLOCK_NAME;
4590 blockName = xmlStrndup(start, ctxt->cur - start);
4592 ERROR("Unknown char property");
4595 if (ctxt->atom == NULL) {
4596 ctxt->atom = xmlRegNewAtom(ctxt, type);
4597 if (ctxt->atom != NULL)
4598 ctxt->atom->valuep = blockName;
4599 } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
4600 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4601 type, 0, 0, blockName);
4606 * xmlFAParseCharClassEsc:
4607 * @ctxt: a regexp parser context
4609 * [23] charClassEsc ::= ( SingleCharEsc | MultiCharEsc | catEsc | complEsc )
4610 * [24] SingleCharEsc ::= '\' [nrt\|.?*+(){}#x2D#x5B#x5D#x5E]
4611 * [25] catEsc ::= '\p{' charProp '}'
4612 * [26] complEsc ::= '\P{' charProp '}'
4613 * [37] MultiCharEsc ::= '.' | ('\' [sSiIcCdDwW])
4616 xmlFAParseCharClassEsc(xmlRegParserCtxtPtr ctxt) {
4620 if (ctxt->atom == NULL) {
4621 ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_ANYCHAR);
4622 } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
4623 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4624 XML_REGEXP_ANYCHAR, 0, 0, NULL);
4630 ERROR("Escaped sequence: expecting \\");
4638 ERROR("Expecting '{'");
4642 xmlFAParseCharProp(ctxt);
4644 ERROR("Expecting '}'");
4648 } else if (cur == 'P') {
4651 ERROR("Expecting '{'");
4655 xmlFAParseCharProp(ctxt);
4656 ctxt->atom->neg = 1;
4658 ERROR("Expecting '}'");
4662 } else if ((cur == 'n') || (cur == 'r') || (cur == 't') || (cur == '\\') ||
4663 (cur == '|') || (cur == '.') || (cur == '?') || (cur == '*') ||
4664 (cur == '+') || (cur == '(') || (cur == ')') || (cur == '{') ||
4665 (cur == '}') || (cur == 0x2D) || (cur == 0x5B) || (cur == 0x5D) ||
4667 if (ctxt->atom == NULL) {
4668 ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_CHARVAL);
4669 if (ctxt->atom != NULL) {
4672 ctxt->atom->codepoint = '\n';
4675 ctxt->atom->codepoint = '\r';
4678 ctxt->atom->codepoint = '\t';
4681 ctxt->atom->codepoint = cur;
4684 } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
4685 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4686 XML_REGEXP_CHARVAL, cur, cur, NULL);
4689 } else if ((cur == 's') || (cur == 'S') || (cur == 'i') || (cur == 'I') ||
4690 (cur == 'c') || (cur == 'C') || (cur == 'd') || (cur == 'D') ||
4691 (cur == 'w') || (cur == 'W')) {
4692 xmlRegAtomType type = XML_REGEXP_ANYSPACE;
4696 type = XML_REGEXP_ANYSPACE;
4699 type = XML_REGEXP_NOTSPACE;
4702 type = XML_REGEXP_INITNAME;
4705 type = XML_REGEXP_NOTINITNAME;
4708 type = XML_REGEXP_NAMECHAR;
4711 type = XML_REGEXP_NOTNAMECHAR;
4714 type = XML_REGEXP_DECIMAL;
4717 type = XML_REGEXP_NOTDECIMAL;
4720 type = XML_REGEXP_REALCHAR;
4723 type = XML_REGEXP_NOTREALCHAR;
4727 if (ctxt->atom == NULL) {
4728 ctxt->atom = xmlRegNewAtom(ctxt, type);
4729 } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
4730 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4737 * xmlFAParseCharRef:
4738 * @ctxt: a regexp parser context
4740 * [19] XmlCharRef ::= ( '&#' [0-9]+ ';' ) | (' &#x' [0-9a-fA-F]+ ';' )
4743 xmlFAParseCharRef(xmlRegParserCtxtPtr ctxt) {
4746 if ((CUR != '&') || (NXT(1) != '#'))
4754 if (((cur >= '0') && (cur <= '9')) ||
4755 ((cur >= 'a') && (cur <= 'f')) ||
4756 ((cur >= 'A') && (cur <= 'F'))) {
4757 while (((cur >= '0') && (cur <= '9')) ||
4758 ((cur >= 'a') && (cur <= 'f')) ||
4759 ((cur >= 'A') && (cur <= 'F'))) {
4760 if ((cur >= '0') && (cur <= '9'))
4761 ret = ret * 16 + cur - '0';
4762 else if ((cur >= 'a') && (cur <= 'f'))
4763 ret = ret * 16 + 10 + (cur - 'a');
4765 ret = ret * 16 + 10 + (cur - 'A');
4770 ERROR("Char ref: expecting [0-9A-F]");
4774 if ((cur >= '0') && (cur <= '9')) {
4775 while ((cur >= '0') && (cur <= '9')) {
4776 ret = ret * 10 + cur - '0';
4781 ERROR("Char ref: expecting [0-9]");
4786 ERROR("Char ref: expecting ';'");
4795 * xmlFAParseCharRange:
4796 * @ctxt: a regexp parser context
4798 * [17] charRange ::= seRange | XmlCharRef | XmlCharIncDash
4799 * [18] seRange ::= charOrEsc '-' charOrEsc
4800 * [20] charOrEsc ::= XmlChar | SingleCharEsc
4801 * [21] XmlChar ::= [^\#x2D#x5B#x5D]
4802 * [22] XmlCharIncDash ::= [^\#x5B#x5D]
4805 xmlFAParseCharRange(xmlRegParserCtxtPtr ctxt) {
4811 ERROR("Expecting ']'");
4815 if ((CUR == '&') && (NXT(1) == '#')) {
4816 end = start = xmlFAParseCharRef(ctxt);
4817 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4818 XML_REGEXP_CHARVAL, start, end, NULL);
4826 case 'n': start = 0xA; break;
4827 case 'r': start = 0xD; break;
4828 case 't': start = 0x9; break;
4829 case '\\': case '|': case '.': case '-': case '^': case '?':
4830 case '*': case '+': case '{': case '}': case '(': case ')':
4834 ERROR("Invalid escape value");
4839 } else if ((cur != 0x5B) && (cur != 0x5D)) {
4840 end = start = CUR_SCHAR(ctxt->cur, len);
4842 ERROR("Expecting a char range");
4850 if ((cur != '-') || (NXT(1) == ']')) {
4851 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4852 XML_REGEXP_CHARVAL, start, end, NULL);
4861 case 'n': end = 0xA; break;
4862 case 'r': end = 0xD; break;
4863 case 't': end = 0x9; break;
4864 case '\\': case '|': case '.': case '-': case '^': case '?':
4865 case '*': case '+': case '{': case '}': case '(': case ')':
4869 ERROR("Invalid escape value");
4873 } else if ((cur != 0x5B) && (cur != 0x5D)) {
4874 end = CUR_SCHAR(ctxt->cur, len);
4876 ERROR("Expecting the end of a char range");
4880 /* TODO check that the values are acceptable character ranges for XML */
4882 ERROR("End of range is before start of range");
4884 xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4885 XML_REGEXP_CHARVAL, start, end, NULL);
4891 * xmlFAParsePosCharGroup:
4892 * @ctxt: a regexp parser context
4894 * [14] posCharGroup ::= ( charRange | charClassEsc )+
4897 xmlFAParsePosCharGroup(xmlRegParserCtxtPtr ctxt) {
4899 if ((CUR == '\\') || (CUR == '.')) {
4900 xmlFAParseCharClassEsc(ctxt);
4902 xmlFAParseCharRange(ctxt);
4904 } while ((CUR != ']') && (CUR != '^') && (CUR != '-') &&
4905 (CUR != 0) && (ctxt->error == 0));
4909 * xmlFAParseCharGroup:
4910 * @ctxt: a regexp parser context
4912 * [13] charGroup ::= posCharGroup | negCharGroup | charClassSub
4913 * [15] negCharGroup ::= '^' posCharGroup
4914 * [16] charClassSub ::= ( posCharGroup | negCharGroup ) '-' charClassExpr
4915 * [12] charClassExpr ::= '[' charGroup ']'
4918 xmlFAParseCharGroup(xmlRegParserCtxtPtr ctxt) {
4920 while ((CUR != ']') && (ctxt->error == 0)) {
4922 int neg = ctxt->neg;
4925 ctxt->neg = !ctxt->neg;
4926 xmlFAParsePosCharGroup(ctxt);
4928 } else if ((CUR == '-') && (NXT(1) == '[')) {
4929 int neg = ctxt->neg;
4931 NEXT; /* eat the '-' */
4932 NEXT; /* eat the '[' */
4933 xmlFAParseCharGroup(ctxt);
4937 ERROR("charClassExpr: ']' expected");
4942 } else if (CUR != ']') {
4943 xmlFAParsePosCharGroup(ctxt);
4950 * xmlFAParseCharClass:
4951 * @ctxt: a regexp parser context
4953 * [11] charClass ::= charClassEsc | charClassExpr
4954 * [12] charClassExpr ::= '[' charGroup ']'
4957 xmlFAParseCharClass(xmlRegParserCtxtPtr ctxt) {
4960 ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_RANGES);
4961 if (ctxt->atom == NULL)
4963 xmlFAParseCharGroup(ctxt);
4967 ERROR("xmlFAParseCharClass: ']' expected");
4970 xmlFAParseCharClassEsc(ctxt);
4975 * xmlFAParseQuantExact:
4976 * @ctxt: a regexp parser context
4978 * [8] QuantExact ::= [0-9]+
4980 * Returns 0 if success or -1 in case of error
4983 xmlFAParseQuantExact(xmlRegParserCtxtPtr ctxt) {
4987 while ((CUR >= '0') && (CUR <= '9')) {
4988 ret = ret * 10 + (CUR - '0');
4999 * xmlFAParseQuantifier:
5000 * @ctxt: a regexp parser context
5002 * [4] quantifier ::= [?*+] | ( '{' quantity '}' )
5003 * [5] quantity ::= quantRange | quantMin | QuantExact
5004 * [6] quantRange ::= QuantExact ',' QuantExact
5005 * [7] quantMin ::= QuantExact ','
5006 * [8] QuantExact ::= [0-9]+
5009 xmlFAParseQuantifier(xmlRegParserCtxtPtr ctxt) {
5013 if ((cur == '?') || (cur == '*') || (cur == '+')) {
5014 if (ctxt->atom != NULL) {
5016 ctxt->atom->quant = XML_REGEXP_QUANT_OPT;
5017 else if (cur == '*')
5018 ctxt->atom->quant = XML_REGEXP_QUANT_MULT;
5019 else if (cur == '+')
5020 ctxt->atom->quant = XML_REGEXP_QUANT_PLUS;
5026 int min = 0, max = 0;
5029 cur = xmlFAParseQuantExact(ctxt);
5037 cur = xmlFAParseQuantExact(ctxt);
5041 ERROR("Improper quantifier");
5048 ERROR("Unterminated quantifier");
5052 if (ctxt->atom != NULL) {
5053 ctxt->atom->quant = XML_REGEXP_QUANT_RANGE;
5054 ctxt->atom->min = min;
5055 ctxt->atom->max = max;
5064 * @ctxt: a regexp parser context
5066 * [9] atom ::= Char | charClass | ( '(' regExp ')' )
5069 xmlFAParseAtom(xmlRegParserCtxtPtr ctxt) {
5072 codepoint = xmlFAIsChar(ctxt);
5073 if (codepoint > 0) {
5074 ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_CHARVAL);
5075 if (ctxt->atom == NULL)
5077 codepoint = CUR_SCHAR(ctxt->cur, len);
5078 ctxt->atom->codepoint = codepoint;
5081 } else if (CUR == '|') {
5083 } else if (CUR == 0) {
5085 } else if (CUR == ')') {
5087 } else if (CUR == '(') {
5088 xmlRegStatePtr start, oldend;
5091 xmlFAGenerateEpsilonTransition(ctxt, ctxt->state, NULL);
5092 start = ctxt->state;
5096 xmlFAParseRegExp(ctxt, 0);
5100 ERROR("xmlFAParseAtom: expecting ')'");
5102 ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_SUBREG);
5103 if (ctxt->atom == NULL)
5105 ctxt->atom->start = start;
5106 ctxt->atom->stop = ctxt->state;
5109 } else if ((CUR == '[') || (CUR == '\\') || (CUR == '.')) {
5110 xmlFAParseCharClass(ctxt);
5118 * @ctxt: a regexp parser context
5120 * [3] piece ::= atom quantifier?
5123 xmlFAParsePiece(xmlRegParserCtxtPtr ctxt) {
5127 ret = xmlFAParseAtom(ctxt);
5130 if (ctxt->atom == NULL) {
5131 ERROR("internal: no atom generated");
5133 xmlFAParseQuantifier(ctxt);
5139 * @ctxt: a regexp parser context
5140 * @to: optional target to the end of the branch
5142 * @to is used to optimize by removing duplicate path in automata
5143 * in expressions like (a|b)(c|d)
5145 * [2] branch ::= piece*
5148 xmlFAParseBranch(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr to) {
5149 xmlRegStatePtr previous;
5152 previous = ctxt->state;
5153 ret = xmlFAParsePiece(ctxt);
5155 if (xmlFAGenerateTransitions(ctxt, previous,
5156 (CUR=='|' || CUR==')') ? to : NULL, ctxt->atom) < 0)
5158 previous = ctxt->state;
5161 while ((ret != 0) && (ctxt->error == 0)) {
5162 ret = xmlFAParsePiece(ctxt);
5164 if (xmlFAGenerateTransitions(ctxt, previous,
5165 (CUR=='|' || CUR==')') ? to : NULL, ctxt->atom) < 0)
5167 previous = ctxt->state;
5176 * @ctxt: a regexp parser context
5177 * @top: is this the top-level expression ?
5179 * [1] regExp ::= branch ( '|' branch )*
5182 xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top) {
5183 xmlRegStatePtr start, end;
5185 /* if not top start should have been generated by an epsilon trans */
5186 start = ctxt->state;
5188 xmlFAParseBranch(ctxt, NULL);
5190 #ifdef DEBUG_REGEXP_GRAPH
5191 printf("State %d is final\n", ctxt->state->no);
5193 ctxt->state->type = XML_REGEXP_FINAL_STATE;
5196 ctxt->end = ctxt->state;
5200 while ((CUR == '|') && (ctxt->error == 0)) {
5202 ctxt->state = start;
5204 xmlFAParseBranch(ctxt, end);
5212 /************************************************************************
5216 ************************************************************************/
5220 * @output: the file for the output debug
5221 * @regexp: the compiled regexp
5223 * Print the content of the compiled regular expression
5226 xmlRegexpPrint(FILE *output, xmlRegexpPtr regexp) {
5231 fprintf(output, " regexp: ");
5232 if (regexp == NULL) {
5233 fprintf(output, "NULL\n");
5236 fprintf(output, "'%s' ", regexp->string);
5237 fprintf(output, "\n");
5238 fprintf(output, "%d atoms:\n", regexp->nbAtoms);
5239 for (i = 0;i < regexp->nbAtoms; i++) {
5240 fprintf(output, " %02d ", i);
5241 xmlRegPrintAtom(output, regexp->atoms[i]);
5243 fprintf(output, "%d states:", regexp->nbStates);
5244 fprintf(output, "\n");
5245 for (i = 0;i < regexp->nbStates; i++) {
5246 xmlRegPrintState(output, regexp->states[i]);
5248 fprintf(output, "%d counters:\n", regexp->nbCounters);
5249 for (i = 0;i < regexp->nbCounters; i++) {
5250 fprintf(output, " %d: min %d max %d\n", i, regexp->counters[i].min,
5251 regexp->counters[i].max);
5257 * @regexp: a regular expression string
5259 * Parses a regular expression conforming to XML Schemas Part 2 Datatype
5260 * Appendix F and builds an automata suitable for testing strings against
5261 * that regular expression
5263 * Returns the compiled expression or NULL in case of error
5266 xmlRegexpCompile(const xmlChar *regexp) {
5268 xmlRegParserCtxtPtr ctxt;
5270 ctxt = xmlRegNewParserCtxt(regexp);
5274 /* initialize the parser */
5276 ctxt->start = ctxt->state = xmlRegNewState(ctxt);
5277 xmlRegStatePush(ctxt, ctxt->start);
5279 /* parse the expression building an automata */
5280 xmlFAParseRegExp(ctxt, 1);
5282 ERROR("xmlFAParseRegExp: extra characters");
5284 ctxt->end = ctxt->state;
5285 ctxt->start->type = XML_REGEXP_START_STATE;
5286 ctxt->end->type = XML_REGEXP_FINAL_STATE;
5288 /* remove the Epsilon except for counted transitions */
5289 xmlFAEliminateEpsilonTransitions(ctxt);
5292 if (ctxt->error != 0) {
5293 xmlRegFreeParserCtxt(ctxt);
5296 ret = xmlRegEpxFromParse(ctxt);
5297 xmlRegFreeParserCtxt(ctxt);
5303 * @comp: the compiled regular expression
5304 * @content: the value to check against the regular expression
5306 * Check if the regular expression generates the value
5308 * Returns 1 if it matches, 0 if not and a negative value in case of error
5311 xmlRegexpExec(xmlRegexpPtr comp, const xmlChar *content) {
5312 if ((comp == NULL) || (content == NULL))
5314 return(xmlFARegExec(comp, content));
5318 * xmlRegexpIsDeterminist:
5319 * @comp: the compiled regular expression
5321 * Check if the regular expression is determinist
5323 * Returns 1 if it yes, 0 if not and a negative value in case of error
5326 xmlRegexpIsDeterminist(xmlRegexpPtr comp) {
5332 if (comp->determinist != -1)
5333 return(comp->determinist);
5335 am = xmlNewAutomata();
5336 if (am->states != NULL) {
5339 for (i = 0;i < am->nbStates;i++)
5340 xmlRegFreeState(am->states[i]);
5341 xmlFree(am->states);
5343 am->nbAtoms = comp->nbAtoms;
5344 am->atoms = comp->atoms;
5345 am->nbStates = comp->nbStates;
5346 am->states = comp->states;
5347 am->determinist = -1;
5348 ret = xmlFAComputesDeterminism(am);
5351 xmlFreeAutomata(am);
5357 * @regexp: the regexp
5362 xmlRegFreeRegexp(xmlRegexpPtr regexp) {
5367 if (regexp->string != NULL)
5368 xmlFree(regexp->string);
5369 if (regexp->states != NULL) {
5370 for (i = 0;i < regexp->nbStates;i++)
5371 xmlRegFreeState(regexp->states[i]);
5372 xmlFree(regexp->states);
5374 if (regexp->atoms != NULL) {
5375 for (i = 0;i < regexp->nbAtoms;i++)
5376 xmlRegFreeAtom(regexp->atoms[i]);
5377 xmlFree(regexp->atoms);
5379 if (regexp->counters != NULL)
5380 xmlFree(regexp->counters);
5381 if (regexp->compact != NULL)
5382 xmlFree(regexp->compact);
5383 if (regexp->transdata != NULL)
5384 xmlFree(regexp->transdata);
5385 if (regexp->stringMap != NULL) {
5386 for (i = 0; i < regexp->nbstrings;i++)
5387 xmlFree(regexp->stringMap[i]);
5388 xmlFree(regexp->stringMap);
5394 #ifdef LIBXML_AUTOMATA_ENABLED
5395 /************************************************************************
5397 * The Automata interface *
5399 ************************************************************************/
5404 * Create a new automata
5406 * Returns the new object or NULL in case of failure
5409 xmlNewAutomata(void) {
5410 xmlAutomataPtr ctxt;
5412 ctxt = xmlRegNewParserCtxt(NULL);
5416 /* initialize the parser */
5418 ctxt->start = ctxt->state = xmlRegNewState(ctxt);
5419 if (ctxt->start == NULL) {
5420 xmlFreeAutomata(ctxt);
5423 ctxt->start->type = XML_REGEXP_START_STATE;
5424 if (xmlRegStatePush(ctxt, ctxt->start) < 0) {
5425 xmlRegFreeState(ctxt->start);
5426 xmlFreeAutomata(ctxt);
5440 xmlFreeAutomata(xmlAutomataPtr am) {
5443 xmlRegFreeParserCtxt(am);
5447 * xmlAutomataGetInitState:
5450 * Initial state lookup
5452 * Returns the initial state of the automata
5455 xmlAutomataGetInitState(xmlAutomataPtr am) {
5462 * xmlAutomataSetFinalState:
5464 * @state: a state in this automata
5466 * Makes that state a final state
5468 * Returns 0 or -1 in case of error
5471 xmlAutomataSetFinalState(xmlAutomataPtr am, xmlAutomataStatePtr state) {
5472 if ((am == NULL) || (state == NULL))
5474 state->type = XML_REGEXP_FINAL_STATE;
5479 * xmlAutomataNewTransition:
5481 * @from: the starting point of the transition
5482 * @to: the target point of the transition or NULL
5483 * @token: the input string associated to that transition
5484 * @data: data passed to the callback function if the transition is activated
5486 * If @to is NULL, this creates first a new target state in the automata
5487 * and then adds a transition from the @from state to the target state
5488 * activated by the value of @token
5490 * Returns the target state or NULL in case of error
5493 xmlAutomataNewTransition(xmlAutomataPtr am, xmlAutomataStatePtr from,
5494 xmlAutomataStatePtr to, const xmlChar *token,
5498 if ((am == NULL) || (from == NULL) || (token == NULL))
5500 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5506 atom->valuep = xmlStrdup(token);
5508 if (xmlFAGenerateTransitions(am, from, to, atom) < 0) {
5509 xmlRegFreeAtom(atom);
5518 * xmlAutomataNewTransition2:
5520 * @from: the starting point of the transition
5521 * @to: the target point of the transition or NULL
5522 * @token: the first input string associated to that transition
5523 * @token2: the second input string associated to that transition
5524 * @data: data passed to the callback function if the transition is activated
5526 * If @to is NULL, this creates first a new target state in the automata
5527 * and then adds a transition from the @from state to the target state
5528 * activated by the value of @token
5530 * Returns the target state or NULL in case of error
5533 xmlAutomataNewTransition2(xmlAutomataPtr am, xmlAutomataStatePtr from,
5534 xmlAutomataStatePtr to, const xmlChar *token,
5535 const xmlChar *token2, void *data) {
5538 if ((am == NULL) || (from == NULL) || (token == NULL))
5540 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5544 if ((token2 == NULL) || (*token2 == 0)) {
5545 atom->valuep = xmlStrdup(token);
5550 lenn = strlen((char *) token2);
5551 lenp = strlen((char *) token);
5553 str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
5555 xmlRegFreeAtom(atom);
5558 memcpy(&str[0], token, lenp);
5560 memcpy(&str[lenp + 1], token2, lenn);
5561 str[lenn + lenp + 1] = 0;
5566 if (xmlFAGenerateTransitions(am, from, to, atom) < 0) {
5567 xmlRegFreeAtom(atom);
5576 * xmlAutomataNewNegTrans:
5578 * @from: the starting point of the transition
5579 * @to: the target point of the transition or NULL
5580 * @token: the first input string associated to that transition
5581 * @token2: the second input string associated to that transition
5582 * @data: data passed to the callback function if the transition is activated
5584 * If @to is NULL, this creates first a new target state in the automata
5585 * and then adds a transition from the @from state to the target state
5586 * activated by any value except (@token,@token2)
5587 * Note that if @token2 is not NULL, then (X, NULL) won't match to follow
5588 # the semantic of XSD ##other
5590 * Returns the target state or NULL in case of error
5593 xmlAutomataNewNegTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
5594 xmlAutomataStatePtr to, const xmlChar *token,
5595 const xmlChar *token2, void *data) {
5597 xmlChar err_msg[200];
5599 if ((am == NULL) || (from == NULL) || (token == NULL))
5601 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5606 if ((token2 == NULL) || (*token2 == 0)) {
5607 atom->valuep = xmlStrdup(token);
5612 lenn = strlen((char *) token2);
5613 lenp = strlen((char *) token);
5615 str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
5617 xmlRegFreeAtom(atom);
5620 memcpy(&str[0], token, lenp);
5622 memcpy(&str[lenp + 1], token2, lenn);
5623 str[lenn + lenp + 1] = 0;
5627 snprintf((char *) err_msg, 199, "not %s", (const char *) atom->valuep);
5629 atom->valuep2 = xmlStrdup(err_msg);
5631 if (xmlFAGenerateTransitions(am, from, to, atom) < 0) {
5632 xmlRegFreeAtom(atom);
5642 * xmlAutomataNewCountTrans2:
5644 * @from: the starting point of the transition
5645 * @to: the target point of the transition or NULL
5646 * @token: the input string associated to that transition
5647 * @token2: the second input string associated to that transition
5648 * @min: the minimum successive occurences of token
5649 * @max: the maximum successive occurences of token
5650 * @data: data associated to the transition
5652 * If @to is NULL, this creates first a new target state in the automata
5653 * and then adds a transition from the @from state to the target state
5654 * activated by a succession of input of value @token and @token2 and
5655 * whose number is between @min and @max
5657 * Returns the target state or NULL in case of error
5660 xmlAutomataNewCountTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from,
5661 xmlAutomataStatePtr to, const xmlChar *token,
5662 const xmlChar *token2,
5663 int min, int max, void *data) {
5667 if ((am == NULL) || (from == NULL) || (token == NULL))
5671 if ((max < min) || (max < 1))
5673 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5676 if ((token2 == NULL) || (*token2 == 0)) {
5677 atom->valuep = xmlStrdup(token);
5682 lenn = strlen((char *) token2);
5683 lenp = strlen((char *) token);
5685 str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
5687 xmlRegFreeAtom(atom);
5690 memcpy(&str[0], token, lenp);
5692 memcpy(&str[lenp + 1], token2, lenn);
5693 str[lenn + lenp + 1] = 0;
5705 * associate a counter to the transition.
5707 counter = xmlRegGetCounter(am);
5708 am->counters[counter].min = min;
5709 am->counters[counter].max = max;
5711 /* xmlFAGenerateTransitions(am, from, to, atom); */
5713 to = xmlRegNewState(am);
5714 xmlRegStatePush(am, to);
5716 xmlRegStateAddTrans(am, from, atom, to, counter, -1);
5717 xmlRegAtomPush(am, atom);
5725 xmlFAGenerateEpsilonTransition(am, from, to);
5730 * xmlAutomataNewCountTrans:
5732 * @from: the starting point of the transition
5733 * @to: the target point of the transition or NULL
5734 * @token: the input string associated to that transition
5735 * @min: the minimum successive occurences of token
5736 * @max: the maximum successive occurences of token
5737 * @data: data associated to the transition
5739 * If @to is NULL, this creates first a new target state in the automata
5740 * and then adds a transition from the @from state to the target state
5741 * activated by a succession of input of value @token and whose number
5742 * is between @min and @max
5744 * Returns the target state or NULL in case of error
5747 xmlAutomataNewCountTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
5748 xmlAutomataStatePtr to, const xmlChar *token,
5749 int min, int max, void *data) {
5753 if ((am == NULL) || (from == NULL) || (token == NULL))
5757 if ((max < min) || (max < 1))
5759 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5762 atom->valuep = xmlStrdup(token);
5771 * associate a counter to the transition.
5773 counter = xmlRegGetCounter(am);
5774 am->counters[counter].min = min;
5775 am->counters[counter].max = max;
5777 /* xmlFAGenerateTransitions(am, from, to, atom); */
5779 to = xmlRegNewState(am);
5780 xmlRegStatePush(am, to);
5782 xmlRegStateAddTrans(am, from, atom, to, counter, -1);
5783 xmlRegAtomPush(am, atom);
5791 xmlFAGenerateEpsilonTransition(am, from, to);
5796 * xmlAutomataNewOnceTrans2:
5798 * @from: the starting point of the transition
5799 * @to: the target point of the transition or NULL
5800 * @token: the input string associated to that transition
5801 * @token2: the second input string associated to that transition
5802 * @min: the minimum successive occurences of token
5803 * @max: the maximum successive occurences of token
5804 * @data: data associated to the transition
5806 * If @to is NULL, this creates first a new target state in the automata
5807 * and then adds a transition from the @from state to the target state
5808 * activated by a succession of input of value @token and @token2 and whose
5809 * number is between @min and @max, moreover that transition can only be
5812 * Returns the target state or NULL in case of error
5815 xmlAutomataNewOnceTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from,
5816 xmlAutomataStatePtr to, const xmlChar *token,
5817 const xmlChar *token2,
5818 int min, int max, void *data) {
5822 if ((am == NULL) || (from == NULL) || (token == NULL))
5826 if ((max < min) || (max < 1))
5828 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5831 if ((token2 == NULL) || (*token2 == 0)) {
5832 atom->valuep = xmlStrdup(token);
5837 lenn = strlen((char *) token2);
5838 lenp = strlen((char *) token);
5840 str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
5842 xmlRegFreeAtom(atom);
5845 memcpy(&str[0], token, lenp);
5847 memcpy(&str[lenp + 1], token2, lenn);
5848 str[lenn + lenp + 1] = 0;
5853 atom->quant = XML_REGEXP_QUANT_ONCEONLY;
5857 * associate a counter to the transition.
5859 counter = xmlRegGetCounter(am);
5860 am->counters[counter].min = 1;
5861 am->counters[counter].max = 1;
5863 /* xmlFAGenerateTransitions(am, from, to, atom); */
5865 to = xmlRegNewState(am);
5866 xmlRegStatePush(am, to);
5868 xmlRegStateAddTrans(am, from, atom, to, counter, -1);
5869 xmlRegAtomPush(am, atom);
5877 * xmlAutomataNewOnceTrans:
5879 * @from: the starting point of the transition
5880 * @to: the target point of the transition or NULL
5881 * @token: the input string associated to that transition
5882 * @min: the minimum successive occurences of token
5883 * @max: the maximum successive occurences of token
5884 * @data: data associated to the transition
5886 * If @to is NULL, this creates first a new target state in the automata
5887 * and then adds a transition from the @from state to the target state
5888 * activated by a succession of input of value @token and whose number
5889 * is between @min and @max, moreover that transition can only be crossed
5892 * Returns the target state or NULL in case of error
5895 xmlAutomataNewOnceTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
5896 xmlAutomataStatePtr to, const xmlChar *token,
5897 int min, int max, void *data) {
5901 if ((am == NULL) || (from == NULL) || (token == NULL))
5905 if ((max < min) || (max < 1))
5907 atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5910 atom->valuep = xmlStrdup(token);
5912 atom->quant = XML_REGEXP_QUANT_ONCEONLY;
5916 * associate a counter to the transition.
5918 counter = xmlRegGetCounter(am);
5919 am->counters[counter].min = 1;
5920 am->counters[counter].max = 1;
5922 /* xmlFAGenerateTransitions(am, from, to, atom); */
5924 to = xmlRegNewState(am);
5925 xmlRegStatePush(am, to);
5927 xmlRegStateAddTrans(am, from, atom, to, counter, -1);
5928 xmlRegAtomPush(am, atom);
5934 * xmlAutomataNewState:
5937 * Create a new disconnected state in the automata
5939 * Returns the new state or NULL in case of error
5942 xmlAutomataNewState(xmlAutomataPtr am) {
5943 xmlAutomataStatePtr to;
5947 to = xmlRegNewState(am);
5948 xmlRegStatePush(am, to);
5953 * xmlAutomataNewEpsilon:
5955 * @from: the starting point of the transition
5956 * @to: the target point of the transition or NULL
5958 * If @to is NULL, this creates first a new target state in the automata
5959 * and then adds an epsilon transition from the @from state to the
5962 * Returns the target state or NULL in case of error
5965 xmlAutomataNewEpsilon(xmlAutomataPtr am, xmlAutomataStatePtr from,
5966 xmlAutomataStatePtr to) {
5967 if ((am == NULL) || (from == NULL))
5969 xmlFAGenerateEpsilonTransition(am, from, to);
5976 * xmlAutomataNewAllTrans:
5978 * @from: the starting point of the transition
5979 * @to: the target point of the transition or NULL
5980 * @lax: allow to transition if not all all transitions have been activated
5982 * If @to is NULL, this creates first a new target state in the automata
5983 * and then adds a an ALL transition from the @from state to the
5984 * target state. That transition is an epsilon transition allowed only when
5985 * all transitions from the @from node have been activated.
5987 * Returns the target state or NULL in case of error
5990 xmlAutomataNewAllTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
5991 xmlAutomataStatePtr to, int lax) {
5992 if ((am == NULL) || (from == NULL))
5994 xmlFAGenerateAllTransition(am, from, to, lax);
6001 * xmlAutomataNewCounter:
6003 * @min: the minimal value on the counter
6004 * @max: the maximal value on the counter
6006 * Create a new counter
6008 * Returns the counter number or -1 in case of error
6011 xmlAutomataNewCounter(xmlAutomataPtr am, int min, int max) {
6017 ret = xmlRegGetCounter(am);
6020 am->counters[ret].min = min;
6021 am->counters[ret].max = max;
6026 * xmlAutomataNewCountedTrans:
6028 * @from: the starting point of the transition
6029 * @to: the target point of the transition or NULL
6030 * @counter: the counter associated to that transition
6032 * If @to is NULL, this creates first a new target state in the automata
6033 * and then adds an epsilon transition from the @from state to the target state
6034 * which will increment the counter provided
6036 * Returns the target state or NULL in case of error
6039 xmlAutomataNewCountedTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6040 xmlAutomataStatePtr to, int counter) {
6041 if ((am == NULL) || (from == NULL) || (counter < 0))
6043 xmlFAGenerateCountedEpsilonTransition(am, from, to, counter);
6050 * xmlAutomataNewCounterTrans:
6052 * @from: the starting point of the transition
6053 * @to: the target point of the transition or NULL
6054 * @counter: the counter associated to that transition
6056 * If @to is NULL, this creates first a new target state in the automata
6057 * and then adds an epsilon transition from the @from state to the target state
6058 * which will be allowed only if the counter is within the right range.
6060 * Returns the target state or NULL in case of error
6063 xmlAutomataNewCounterTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6064 xmlAutomataStatePtr to, int counter) {
6065 if ((am == NULL) || (from == NULL) || (counter < 0))
6067 xmlFAGenerateCountedTransition(am, from, to, counter);
6074 * xmlAutomataCompile:
6077 * Compile the automata into a Reg Exp ready for being executed.
6078 * The automata should be free after this point.
6080 * Returns the compiled regexp or NULL in case of error
6083 xmlAutomataCompile(xmlAutomataPtr am) {
6086 if ((am == NULL) || (am->error != 0)) return(NULL);
6087 xmlFAEliminateEpsilonTransitions(am);
6088 /* xmlFAComputesDeterminism(am); */
6089 ret = xmlRegEpxFromParse(am);
6095 * xmlAutomataIsDeterminist:
6098 * Checks if an automata is determinist.
6100 * Returns 1 if true, 0 if not, and -1 in case of error
6103 xmlAutomataIsDeterminist(xmlAutomataPtr am) {
6109 ret = xmlFAComputesDeterminism(am);
6112 #endif /* LIBXML_AUTOMATA_ENABLED */
6114 #ifdef LIBXML_EXPR_ENABLED
6115 /************************************************************************
6117 * Formal Expression handling code *
6119 ************************************************************************/
6120 /************************************************************************
6122 * Expression handling context *
6124 ************************************************************************/
6126 struct _xmlExpCtxt {
6128 xmlExpNodePtr *table;
6140 * @maxNodes: the maximum number of nodes
6141 * @dict: optional dictionnary to use internally
6143 * Creates a new context for manipulating expressions
6145 * Returns the context or NULL in case of error
6148 xmlExpNewCtxt(int maxNodes, xmlDictPtr dict) {
6152 if (maxNodes <= 4096)
6155 ret = (xmlExpCtxtPtr) xmlMalloc(sizeof(xmlExpCtxt));
6158 memset(ret, 0, sizeof(xmlExpCtxt));
6161 ret->table = xmlMalloc(size * sizeof(xmlExpNodePtr));
6162 if (ret->table == NULL) {
6166 memset(ret->table, 0, size * sizeof(xmlExpNodePtr));
6168 ret->dict = xmlDictCreate();
6169 if (ret->dict == NULL) {
6170 xmlFree(ret->table);
6176 xmlDictReference(ret->dict);
6183 * @ctxt: an expression context
6185 * Free an expression context
6188 xmlExpFreeCtxt(xmlExpCtxtPtr ctxt) {
6191 xmlDictFree(ctxt->dict);
6192 if (ctxt->table != NULL)
6193 xmlFree(ctxt->table);
6197 /************************************************************************
6199 * Structure associated to an expression node *
6201 ************************************************************************/
6202 #define MAX_NODES 10000
6204 /* #define DEBUG_DERIV */
6209 * - public API for creation
6212 * - regression testing
6215 * - split into module and test tool
6220 XML_EXP_NILABLE = (1 << 0)
6223 #define IS_NILLABLE(node) ((node)->info & XML_EXP_NILABLE)
6225 struct _xmlExpNode {
6226 unsigned char type;/* xmlExpNodeType */
6227 unsigned char info;/* OR of xmlExpNodeInfo */
6228 unsigned short key; /* the hash key */
6229 unsigned int ref; /* The number of references */
6230 int c_max; /* the maximum length it can consume */
6231 xmlExpNodePtr exp_left;
6232 xmlExpNodePtr next;/* the next node in the hash table or free list */
6239 xmlExpNodePtr f_right;
6241 const xmlChar *f_str;
6245 #define exp_min field.count.f_min
6246 #define exp_max field.count.f_max
6247 /* #define exp_left field.children.f_left */
6248 #define exp_right field.children.f_right
6249 #define exp_str field.f_str
6251 static xmlExpNodePtr xmlExpNewNode(xmlExpCtxtPtr ctxt, xmlExpNodeType type);
6252 static xmlExpNode forbiddenExpNode = {
6253 XML_EXP_FORBID, 0, 0, 0, 0, NULL, NULL, {{ 0, 0}}
6255 xmlExpNodePtr forbiddenExp = &forbiddenExpNode;
6256 static xmlExpNode emptyExpNode = {
6257 XML_EXP_EMPTY, 1, 0, 0, 0, NULL, NULL, {{ 0, 0}}
6259 xmlExpNodePtr emptyExp = &emptyExpNode;
6261 /************************************************************************
6263 * The custom hash table for unicity and canonicalization *
6264 * of sub-expressions pointers *
6266 ************************************************************************/
6268 * xmlExpHashNameComputeKey:
6269 * Calculate the hash key for a token
6271 static unsigned short
6272 xmlExpHashNameComputeKey(const xmlChar *name) {
6273 unsigned short value = 0L;
6277 value += 30 * (*name);
6278 while ((ch = *name++) != 0) {
6279 value = value ^ ((value << 5) + (value >> 3) + (unsigned long)ch);
6286 * xmlExpHashComputeKey:
6287 * Calculate the hash key for a compound expression
6289 static unsigned short
6290 xmlExpHashComputeKey(xmlExpNodeType type, xmlExpNodePtr left,
6291 xmlExpNodePtr right) {
6292 unsigned long value;
6298 value += right->key;
6300 ret = (unsigned short) value;
6304 value += right->key;
6306 ret = (unsigned short) value;
6310 value += right->key;
6311 ret = (unsigned short) value;
6320 static xmlExpNodePtr
6321 xmlExpNewNode(xmlExpCtxtPtr ctxt, xmlExpNodeType type) {
6324 if (ctxt->nb_nodes >= MAX_NODES)
6326 ret = (xmlExpNodePtr) xmlMalloc(sizeof(xmlExpNode));
6329 memset(ret, 0, sizeof(xmlExpNode));
6338 * xmlExpHashGetEntry:
6339 * @table: the hash table
6341 * Get the unique entry from the hash table. The entry is created if
6342 * needed. @left and @right are consumed, i.e. their ref count will
6343 * be decremented by the operation.
6345 * Returns the pointer or NULL in case of error
6347 static xmlExpNodePtr
6348 xmlExpHashGetEntry(xmlExpCtxtPtr ctxt, xmlExpNodeType type,
6349 xmlExpNodePtr left, xmlExpNodePtr right,
6350 const xmlChar *name, int min, int max) {
6351 unsigned short kbase, key;
6352 xmlExpNodePtr entry;
6353 xmlExpNodePtr insert;
6359 * Check for duplicate and insertion location.
6361 if (type == XML_EXP_ATOM) {
6362 kbase = xmlExpHashNameComputeKey(name);
6363 } else if (type == XML_EXP_COUNT) {
6364 /* COUNT reduction rule 1 */
6371 xmlExpFree(ctxt, left);
6376 xmlExpFree(ctxt, left);
6377 return(forbiddenExp);
6384 } else if (type == XML_EXP_OR) {
6385 /* Forbid reduction rules */
6386 if (left->type == XML_EXP_FORBID) {
6387 xmlExpFree(ctxt, left);
6390 if (right->type == XML_EXP_FORBID) {
6391 xmlExpFree(ctxt, right);
6395 /* OR reduction rule 1 */
6396 /* a | a reduced to a */
6397 if (left == right) {
6401 /* OR canonicalization rule 1 */
6402 /* linearize (a | b) | c into a | (b | c) */
6403 if ((left->type == XML_EXP_OR) && (right->type != XML_EXP_OR)) {
6404 xmlExpNodePtr tmp = left;
6408 /* OR reduction rule 2 */
6409 /* a | (a | b) and b | (a | b) are reduced to a | b */
6410 if (right->type == XML_EXP_OR) {
6411 if ((left == right->exp_left) ||
6412 (left == right->exp_right)) {
6413 xmlExpFree(ctxt, left);
6417 /* OR canonicalization rule 2 */
6418 /* linearize (a | b) | c into a | (b | c) */
6419 if (left->type == XML_EXP_OR) {
6422 /* OR canonicalization rule 2 */
6423 if ((left->exp_right->type != XML_EXP_OR) &&
6424 (left->exp_right->key < left->exp_left->key)) {
6425 tmp = left->exp_right;
6426 left->exp_right = left->exp_left;
6427 left->exp_left = tmp;
6429 left->exp_right->ref++;
6430 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left->exp_right, right,
6432 left->exp_left->ref++;
6433 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left->exp_left, tmp,
6436 xmlExpFree(ctxt, left);
6439 if (right->type == XML_EXP_OR) {
6440 /* Ordering in the tree */
6441 /* C | (A | B) -> A | (B | C) */
6442 if (left->key > right->exp_right->key) {
6444 right->exp_right->ref++;
6445 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_right,
6447 right->exp_left->ref++;
6448 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_left,
6450 xmlExpFree(ctxt, right);
6453 /* Ordering in the tree */
6454 /* B | (A | C) -> A | (B | C) */
6455 if (left->key > right->exp_left->key) {
6457 right->exp_right->ref++;
6458 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left,
6459 right->exp_right, NULL, 0, 0);
6460 right->exp_left->ref++;
6461 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_left,
6463 xmlExpFree(ctxt, right);
6467 /* we know both types are != XML_EXP_OR here */
6468 else if (left->key > right->key) {
6469 xmlExpNodePtr tmp = left;
6473 kbase = xmlExpHashComputeKey(type, left, right);
6474 } else if (type == XML_EXP_SEQ) {
6475 /* Forbid reduction rules */
6476 if (left->type == XML_EXP_FORBID) {
6477 xmlExpFree(ctxt, right);
6480 if (right->type == XML_EXP_FORBID) {
6481 xmlExpFree(ctxt, left);
6484 /* Empty reduction rules */
6485 if (right->type == XML_EXP_EMPTY) {
6488 if (left->type == XML_EXP_EMPTY) {
6491 kbase = xmlExpHashComputeKey(type, left, right);
6495 key = kbase % ctxt->size;
6496 if (ctxt->table[key] != NULL) {
6497 for (insert = ctxt->table[key]; insert != NULL;
6498 insert = insert->next) {
6499 if ((insert->key == kbase) &&
6500 (insert->type == type)) {
6501 if (type == XML_EXP_ATOM) {
6502 if (name == insert->exp_str) {
6506 } else if (type == XML_EXP_COUNT) {
6507 if ((insert->exp_min == min) && (insert->exp_max == max) &&
6508 (insert->exp_left == left)) {
6513 } else if ((insert->exp_left == left) &&
6514 (insert->exp_right == right)) {
6524 entry = xmlExpNewNode(ctxt, type);
6528 if (type == XML_EXP_ATOM) {
6529 entry->exp_str = name;
6531 } else if (type == XML_EXP_COUNT) {
6532 entry->exp_min = min;
6533 entry->exp_max = max;
6534 entry->exp_left = left;
6535 if ((min == 0) || (IS_NILLABLE(left)))
6536 entry->info |= XML_EXP_NILABLE;
6540 entry->c_max = max * entry->exp_left->c_max;
6542 entry->exp_left = left;
6543 entry->exp_right = right;
6544 if (type == XML_EXP_OR) {
6545 if ((IS_NILLABLE(left)) || (IS_NILLABLE(right)))
6546 entry->info |= XML_EXP_NILABLE;
6547 if ((entry->exp_left->c_max == -1) ||
6548 (entry->exp_right->c_max == -1))
6550 else if (entry->exp_left->c_max > entry->exp_right->c_max)
6551 entry->c_max = entry->exp_left->c_max;
6553 entry->c_max = entry->exp_right->c_max;
6555 if ((IS_NILLABLE(left)) && (IS_NILLABLE(right)))
6556 entry->info |= XML_EXP_NILABLE;
6557 if ((entry->exp_left->c_max == -1) ||
6558 (entry->exp_right->c_max == -1))
6561 entry->c_max = entry->exp_left->c_max + entry->exp_right->c_max;
6565 if (ctxt->table[key] != NULL)
6566 entry->next = ctxt->table[key];
6568 ctxt->table[key] = entry;
6576 * @ctxt: the expression context
6577 * @exp: the expression
6579 * Dereference the expression
6582 xmlExpFree(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp) {
6583 if ((exp == NULL) || (exp == forbiddenExp) || (exp == emptyExp))
6586 if (exp->ref == 0) {
6589 /* Unlink it first from the hash table */
6590 key = exp->key % ctxt->size;
6591 if (ctxt->table[key] == exp) {
6592 ctxt->table[key] = exp->next;
6596 tmp = ctxt->table[key];
6597 while (tmp != NULL) {
6598 if (tmp->next == exp) {
6599 tmp->next = exp->next;
6606 if ((exp->type == XML_EXP_SEQ) || (exp->type == XML_EXP_OR)) {
6607 xmlExpFree(ctxt, exp->exp_left);
6608 xmlExpFree(ctxt, exp->exp_right);
6609 } else if (exp->type == XML_EXP_COUNT) {
6610 xmlExpFree(ctxt, exp->exp_left);
6619 * @exp: the expression
6621 * Increase the reference count of the expression
6624 xmlExpRef(xmlExpNodePtr exp) {
6631 * @ctxt: the expression context
6632 * @name: the atom name
6633 * @len: the atom name lenght in byte (or -1);
6635 * Get the atom associated to this name from that context
6637 * Returns the node or NULL in case of error
6640 xmlExpNewAtom(xmlExpCtxtPtr ctxt, const xmlChar *name, int len) {
6641 if ((ctxt == NULL) || (name == NULL))
6643 name = xmlDictLookup(ctxt->dict, name, len);
6646 return(xmlExpHashGetEntry(ctxt, XML_EXP_ATOM, NULL, NULL, name, 0, 0));
6651 * @ctxt: the expression context
6652 * @left: left expression
6653 * @right: right expression
6655 * Get the atom associated to the choice @left | @right
6656 * Note that @left and @right are consumed in the operation, to keep
6657 * an handle on them use xmlExpRef() and use xmlExpFree() to release them,
6658 * this is true even in case of failure (unless ctxt == NULL).
6660 * Returns the node or NULL in case of error
6663 xmlExpNewOr(xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right) {
6666 if ((left == NULL) || (right == NULL)) {
6667 xmlExpFree(ctxt, left);
6668 xmlExpFree(ctxt, right);
6671 return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, left, right, NULL, 0, 0));
6676 * @ctxt: the expression context
6677 * @left: left expression
6678 * @right: right expression
6680 * Get the atom associated to the sequence @left , @right
6681 * Note that @left and @right are consumed in the operation, to keep
6682 * an handle on them use xmlExpRef() and use xmlExpFree() to release them,
6683 * this is true even in case of failure (unless ctxt == NULL).
6685 * Returns the node or NULL in case of error
6688 xmlExpNewSeq(xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right) {
6691 if ((left == NULL) || (right == NULL)) {
6692 xmlExpFree(ctxt, left);
6693 xmlExpFree(ctxt, right);
6696 return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, left, right, NULL, 0, 0));
6701 * @ctxt: the expression context
6702 * @subset: the expression to be repeated
6703 * @min: the lower bound for the repetition
6704 * @max: the upper bound for the repetition, -1 means infinite
6706 * Get the atom associated to the range (@subset){@min, @max}
6707 * Note that @subset is consumed in the operation, to keep
6708 * an handle on it use xmlExpRef() and use xmlExpFree() to release it,
6709 * this is true even in case of failure (unless ctxt == NULL).
6711 * Returns the node or NULL in case of error
6714 xmlExpNewRange(xmlExpCtxtPtr ctxt, xmlExpNodePtr subset, int min, int max) {
6717 if ((subset == NULL) || (min < 0) || (max < -1) ||
6718 ((max >= 0) && (min > max))) {
6719 xmlExpFree(ctxt, subset);
6722 return(xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, subset,
6723 NULL, NULL, min, max));
6726 /************************************************************************
6728 * Public API for operations on expressions *
6730 ************************************************************************/
6733 xmlExpGetLanguageInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
6734 const xmlChar**list, int len, int nb) {
6737 switch (exp->type) {
6741 for (tmp = 0;tmp < nb;tmp++)
6742 if (list[tmp] == exp->exp_str)
6746 list[nb++] = exp->exp_str;
6749 exp = exp->exp_left;
6753 tmp = xmlExpGetLanguageInt(ctxt, exp->exp_left, list, len, nb);
6756 tmp2 = xmlExpGetLanguageInt(ctxt, exp->exp_right, list, len,
6766 * xmlExpGetLanguage:
6767 * @ctxt: the expression context
6768 * @exp: the expression
6769 * @langList: where to store the tokens
6770 * @len: the allocated lenght of @list
6772 * Find all the strings used in @exp and store them in @list
6774 * Returns the number of unique strings found, -1 in case of errors and
6775 * -2 if there is more than @len strings
6778 xmlExpGetLanguage(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
6779 const xmlChar**langList, int len) {
6780 if ((ctxt == NULL) || (exp == NULL) || (langList == NULL) || (len <= 0))
6782 return(xmlExpGetLanguageInt(ctxt, exp, langList, len, 0));
6786 xmlExpGetStartInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
6787 const xmlChar**list, int len, int nb) {
6790 switch (exp->type) {
6791 case XML_EXP_FORBID:
6796 for (tmp = 0;tmp < nb;tmp++)
6797 if (list[tmp] == exp->exp_str)
6801 list[nb++] = exp->exp_str;
6804 exp = exp->exp_left;
6807 tmp = xmlExpGetStartInt(ctxt, exp->exp_left, list, len, nb);
6810 if (IS_NILLABLE(exp->exp_left)) {
6811 tmp2 = xmlExpGetStartInt(ctxt, exp->exp_right, list, len,
6819 tmp = xmlExpGetStartInt(ctxt, exp->exp_left, list, len, nb);
6822 tmp2 = xmlExpGetStartInt(ctxt, exp->exp_right, list, len,
6833 * @ctxt: the expression context
6834 * @exp: the expression
6835 * @tokList: where to store the tokens
6836 * @len: the allocated lenght of @list
6838 * Find all the strings that appears at the start of the languages
6839 * accepted by @exp and store them in @list. E.g. for (a, b) | c
6840 * it will return the list [a, c]
6842 * Returns the number of unique strings found, -1 in case of errors and
6843 * -2 if there is more than @len strings
6846 xmlExpGetStart(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
6847 const xmlChar**tokList, int len) {
6848 if ((ctxt == NULL) || (exp == NULL) || (tokList == NULL) || (len <= 0))
6850 return(xmlExpGetStartInt(ctxt, exp, tokList, len, 0));
6855 * @exp: the expression
6857 * Finds if the expression is nillable, i.e. if it accepts the empty sequqnce
6859 * Returns 1 if nillable, 0 if not and -1 in case of error
6862 xmlExpIsNillable(xmlExpNodePtr exp) {
6865 return(IS_NILLABLE(exp) != 0);
6868 static xmlExpNodePtr
6869 xmlExpStringDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar *str)
6873 switch (exp->type) {
6875 return(forbiddenExp);
6876 case XML_EXP_FORBID:
6877 return(forbiddenExp);
6879 if (exp->exp_str == str) {
6881 printf("deriv atom: equal => Empty\n");
6886 printf("deriv atom: mismatch => forbid\n");
6888 /* TODO wildcards here */
6896 printf("deriv or: => or(derivs)\n");
6898 tmp = xmlExpStringDeriveInt(ctxt, exp->exp_left, str);
6902 ret = xmlExpStringDeriveInt(ctxt, exp->exp_right, str);
6904 xmlExpFree(ctxt, tmp);
6907 ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, tmp, ret,
6913 printf("deriv seq: starting with left\n");
6915 ret = xmlExpStringDeriveInt(ctxt, exp->exp_left, str);
6918 } else if (ret == forbiddenExp) {
6919 if (IS_NILLABLE(exp->exp_left)) {
6921 printf("deriv seq: left failed but nillable\n");
6923 ret = xmlExpStringDeriveInt(ctxt, exp->exp_right, str);
6927 printf("deriv seq: left match => sequence\n");
6929 exp->exp_right->ref++;
6930 ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, exp->exp_right,
6934 case XML_EXP_COUNT: {
6938 if (exp->exp_max == 0)
6939 return(forbiddenExp);
6940 ret = xmlExpStringDeriveInt(ctxt, exp->exp_left, str);
6943 if (ret == forbiddenExp) {
6945 printf("deriv count: pattern mismatch => forbid\n");
6949 if (exp->exp_max == 1)
6951 if (exp->exp_max < 0) /* unbounded */
6954 max = exp->exp_max - 1;
6955 if (exp->exp_min > 0)
6956 min = exp->exp_min - 1;
6959 exp->exp_left->ref++;
6960 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left, NULL,
6962 if (ret == emptyExp) {
6964 printf("deriv count: match to empty => new count\n");
6969 printf("deriv count: match => sequence with new count\n");
6971 return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, tmp,
6979 * xmlExpStringDerive:
6980 * @ctxt: the expression context
6981 * @exp: the expression
6983 * @len: the string len in bytes if available
6985 * Do one step of Brzozowski derivation of the expression @exp with
6986 * respect to the input string
6988 * Returns the resulting expression or NULL in case of internal error
6991 xmlExpStringDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
6992 const xmlChar *str, int len) {
6993 const xmlChar *input;
6995 if ((exp == NULL) || (ctxt == NULL) || (str == NULL)) {
6999 * check the string is in the dictionnary, if yes use an interned
7000 * copy, otherwise we know it's not an acceptable input
7002 input = xmlDictExists(ctxt->dict, str, len);
7003 if (input == NULL) {
7004 return(forbiddenExp);
7006 return(xmlExpStringDeriveInt(ctxt, exp, input));
7010 xmlExpCheckCard(xmlExpNodePtr exp, xmlExpNodePtr sub) {
7013 if (sub->c_max == -1) {
7014 if (exp->c_max != -1)
7016 } else if ((exp->c_max >= 0) && (exp->c_max < sub->c_max)) {
7020 if ((IS_NILLABLE(sub)) && (!IS_NILLABLE(exp)))
7026 static xmlExpNodePtr xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7030 * @ctxt: the expressions context
7031 * @exp: the englobing expression
7032 * @sub: the subexpression
7033 * @mult: the multiple expression
7034 * @remain: the remain from the derivation of the multiple
7036 * Check if exp is a multiple of sub, i.e. if there is a finite number n
7037 * so that sub{n} subsume exp
7039 * Returns the multiple value if successful, 0 if it is not a multiple
7040 * and -1 in case of internel error.
7044 xmlExpDivide(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub,
7045 xmlExpNodePtr *mult, xmlExpNodePtr *remain) {
7047 xmlExpNodePtr tmp, tmp2;
7049 if (mult != NULL) *mult = NULL;
7050 if (remain != NULL) *remain = NULL;
7051 if (exp->c_max == -1) return(0);
7052 if (IS_NILLABLE(exp) && (!IS_NILLABLE(sub))) return(0);
7054 for (i = 1;i <= exp->c_max;i++) {
7056 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT,
7057 sub, NULL, NULL, i, i);
7061 if (!xmlExpCheckCard(tmp, exp)) {
7062 xmlExpFree(ctxt, tmp);
7065 tmp2 = xmlExpExpDeriveInt(ctxt, tmp, exp);
7067 xmlExpFree(ctxt, tmp);
7070 if ((tmp2 != forbiddenExp) && (IS_NILLABLE(tmp2))) {
7074 xmlExpFree(ctxt, tmp2);
7078 xmlExpFree(ctxt, tmp);
7080 printf("Divide succeeded %d\n", i);
7084 xmlExpFree(ctxt, tmp);
7085 xmlExpFree(ctxt, tmp2);
7088 printf("Divide failed\n");
7094 * xmlExpExpDeriveInt:
7095 * @ctxt: the expressions context
7096 * @exp: the englobing expression
7097 * @sub: the subexpression
7099 * Try to do a step of Brzozowski derivation but at a higher level
7100 * the input being a subexpression.
7102 * Returns the resulting expression or NULL in case of internal error
7104 static xmlExpNodePtr
7105 xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
7106 xmlExpNodePtr ret, tmp, tmp2, tmp3;
7107 const xmlChar **tab;
7111 * In case of equality and if the expression can only consume a finite
7112 * amount, then the derivation is empty
7114 if ((exp == sub) && (exp->c_max >= 0)) {
7116 printf("Equal(exp, sub) and finite -> Empty\n");
7121 * decompose sub sequence first
7123 if (sub->type == XML_EXP_EMPTY) {
7125 printf("Empty(sub) -> Empty\n");
7130 if (sub->type == XML_EXP_SEQ) {
7132 printf("Seq(sub) -> decompose\n");
7134 tmp = xmlExpExpDeriveInt(ctxt, exp, sub->exp_left);
7137 if (tmp == forbiddenExp)
7139 ret = xmlExpExpDeriveInt(ctxt, tmp, sub->exp_right);
7140 xmlExpFree(ctxt, tmp);
7143 if (sub->type == XML_EXP_OR) {
7145 printf("Or(sub) -> decompose\n");
7147 tmp = xmlExpExpDeriveInt(ctxt, exp, sub->exp_left);
7148 if (tmp == forbiddenExp)
7152 ret = xmlExpExpDeriveInt(ctxt, exp, sub->exp_right);
7153 if ((ret == NULL) || (ret == forbiddenExp)) {
7154 xmlExpFree(ctxt, tmp);
7157 return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, tmp, ret, NULL, 0, 0));
7159 if (!xmlExpCheckCard(exp, sub)) {
7161 printf("CheckCard(exp, sub) failed -> Forbid\n");
7163 return(forbiddenExp);
7165 switch (exp->type) {
7167 if (sub == emptyExp)
7170 printf("Empty(exp) -> Forbid\n");
7172 return(forbiddenExp);
7173 case XML_EXP_FORBID:
7175 printf("Forbid(exp) -> Forbid\n");
7177 return(forbiddenExp);
7179 if (sub->type == XML_EXP_ATOM) {
7180 /* TODO: handle wildcards */
7181 if (exp->exp_str == sub->exp_str) {
7183 printf("Atom match -> Empty\n");
7188 printf("Atom mismatch -> Forbid\n");
7190 return(forbiddenExp);
7192 if ((sub->type == XML_EXP_COUNT) &&
7193 (sub->exp_max == 1) &&
7194 (sub->exp_left->type == XML_EXP_ATOM)) {
7195 /* TODO: handle wildcards */
7196 if (exp->exp_str == sub->exp_left->exp_str) {
7198 printf("Atom match -> Empty\n");
7203 printf("Atom mismatch -> Forbid\n");
7205 return(forbiddenExp);
7208 printf("Compex exp vs Atom -> Forbid\n");
7210 return(forbiddenExp);
7212 /* try to get the sequence consumed only if possible */
7213 if (xmlExpCheckCard(exp->exp_left, sub)) {
7214 /* See if the sequence can be consumed directly */
7216 printf("Seq trying left only\n");
7218 ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub);
7219 if ((ret != forbiddenExp) && (ret != NULL)) {
7221 printf("Seq trying left only worked\n");
7224 * TODO: assumption here that we are determinist
7225 * i.e. we won't get to a nillable exp left
7226 * subset which could be matched by the right
7228 * e.g.: (a | b)+,(a | c) and 'a+,a'
7230 exp->exp_right->ref++;
7231 return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret,
7232 exp->exp_right, NULL, 0, 0));
7236 printf("Seq: left too short\n");
7239 /* Try instead to decompose */
7240 if (sub->type == XML_EXP_COUNT) {
7244 printf("Seq: sub is a count\n");
7246 ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub->exp_left);
7249 if (ret != forbiddenExp) {
7251 printf("Seq , Count match on left\n");
7253 if (sub->exp_max < 0)
7256 max = sub->exp_max -1;
7257 if (sub->exp_min > 0)
7258 min = sub->exp_min -1;
7261 exp->exp_right->ref++;
7262 tmp = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret,
7263 exp->exp_right, NULL, 0, 0);
7267 sub->exp_left->ref++;
7268 tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT,
7269 sub->exp_left, NULL, NULL, min, max);
7271 xmlExpFree(ctxt, tmp);
7274 ret = xmlExpExpDeriveInt(ctxt, tmp, tmp2);
7275 xmlExpFree(ctxt, tmp);
7276 xmlExpFree(ctxt, tmp2);
7280 /* we made no progress on structured operations */
7284 printf("Or , trying both side\n");
7286 ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub);
7289 tmp = xmlExpExpDeriveInt(ctxt, exp->exp_right, sub);
7291 xmlExpFree(ctxt, ret);
7294 return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, tmp, NULL, 0, 0));
7295 case XML_EXP_COUNT: {
7298 if (sub->type == XML_EXP_COUNT) {
7300 * Try to see if the loop is completely subsumed
7302 tmp = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub->exp_left);
7305 if (tmp == forbiddenExp) {
7309 printf("Count, Count inner don't subsume\n");
7311 mult = xmlExpDivide(ctxt, sub->exp_left, exp->exp_left,
7315 printf("Count, Count not multiple => forbidden\n");
7317 return(forbiddenExp);
7319 if (sub->exp_max == -1) {
7321 if (exp->exp_max == -1) {
7322 if (exp->exp_min <= sub->exp_min * mult)
7325 min = exp->exp_min - sub->exp_min * mult;
7328 printf("Count, Count finite can't subsume infinite\n");
7330 xmlExpFree(ctxt, tmp);
7331 return(forbiddenExp);
7334 if (exp->exp_max == -1) {
7336 printf("Infinite loop consume mult finite loop\n");
7338 if (exp->exp_min > sub->exp_min * mult) {
7340 min = exp->exp_min - sub->exp_min * mult;
7346 if (exp->exp_max < sub->exp_max * mult) {
7348 printf("loops max mult mismatch => forbidden\n");
7350 xmlExpFree(ctxt, tmp);
7351 return(forbiddenExp);
7353 if (sub->exp_max * mult > exp->exp_min)
7356 min = exp->exp_min - sub->exp_max * mult;
7357 max = exp->exp_max - sub->exp_max * mult;
7360 } else if (!IS_NILLABLE(tmp)) {
7362 * TODO: loop here to try to grow if working on finite
7366 printf("Count, Count remain not nillable => forbidden\n");
7368 xmlExpFree(ctxt, tmp);
7369 return(forbiddenExp);
7370 } else if (sub->exp_max == -1) {
7371 if (exp->exp_max == -1) {
7372 if (exp->exp_min <= sub->exp_min) {
7374 printf("Infinite loops Okay => COUNT(0,Inf)\n");
7380 printf("Infinite loops min => Count(X,Inf)\n");
7383 min = exp->exp_min - sub->exp_min;
7385 } else if (exp->exp_min > sub->exp_min) {
7387 printf("loops min mismatch 1 => forbidden ???\n");
7389 xmlExpFree(ctxt, tmp);
7390 return(forbiddenExp);
7396 if (exp->exp_max == -1) {
7398 printf("Infinite loop consume finite loop\n");
7400 if (exp->exp_min > sub->exp_min) {
7402 min = exp->exp_min - sub->exp_min;
7408 if (exp->exp_max < sub->exp_max) {
7410 printf("loops max mismatch => forbidden\n");
7412 xmlExpFree(ctxt, tmp);
7413 return(forbiddenExp);
7415 if (sub->exp_max > exp->exp_min)
7418 min = exp->exp_min - sub->exp_max;
7419 max = exp->exp_max - sub->exp_max;
7423 printf("loops match => SEQ(COUNT())\n");
7425 exp->exp_left->ref++;
7426 tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left,
7427 NULL, NULL, min, max);
7431 ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, tmp, tmp2,
7435 tmp = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub);
7438 if (tmp == forbiddenExp) {
7440 printf("loop mismatch => forbidden\n");
7442 return(forbiddenExp);
7444 if (exp->exp_min > 0)
7445 min = exp->exp_min - 1;
7448 if (exp->exp_max < 0)
7451 max = exp->exp_max - 1;
7454 printf("loop match => SEQ(COUNT())\n");
7456 exp->exp_left->ref++;
7457 tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left,
7458 NULL, NULL, min, max);
7461 ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, tmp, tmp2,
7468 printf("Fallback to derivative\n");
7470 if (IS_NILLABLE(sub)) {
7471 if (!(IS_NILLABLE(exp)))
7472 return(forbiddenExp);
7478 * here the structured derivation made no progress so
7479 * we use the default token based derivation to force one more step
7481 if (ctxt->tabSize == 0)
7484 tab = (const xmlChar **) xmlMalloc(ctxt->tabSize *
7485 sizeof(const xmlChar *));
7491 * collect all the strings accepted by the subexpression on input
7493 len = xmlExpGetStartInt(ctxt, sub, tab, ctxt->tabSize, 0);
7495 const xmlChar **temp;
7496 temp = (const xmlChar **) xmlRealloc((xmlChar **) tab, ctxt->tabSize * 2 *
7497 sizeof(const xmlChar *));
7499 xmlFree((xmlChar **) tab);
7504 len = xmlExpGetStartInt(ctxt, sub, tab, ctxt->tabSize, 0);
7506 for (i = 0;i < len;i++) {
7507 tmp = xmlExpStringDeriveInt(ctxt, exp, tab[i]);
7508 if ((tmp == NULL) || (tmp == forbiddenExp)) {
7509 xmlExpFree(ctxt, ret);
7510 xmlFree((xmlChar **) tab);
7513 tmp2 = xmlExpStringDeriveInt(ctxt, sub, tab[i]);
7514 if ((tmp2 == NULL) || (tmp2 == forbiddenExp)) {
7515 xmlExpFree(ctxt, tmp);
7516 xmlExpFree(ctxt, ret);
7517 xmlFree((xmlChar **) tab);
7520 tmp3 = xmlExpExpDeriveInt(ctxt, tmp, tmp2);
7521 xmlExpFree(ctxt, tmp);
7522 xmlExpFree(ctxt, tmp2);
7524 if ((tmp3 == NULL) || (tmp3 == forbiddenExp)) {
7525 xmlExpFree(ctxt, ret);
7526 xmlFree((xmlChar **) tab);
7533 ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, tmp3, NULL, 0, 0);
7535 xmlFree((xmlChar **) tab);
7540 xmlFree((xmlChar **) tab);
7546 * @ctxt: the expressions context
7547 * @exp: the englobing expression
7548 * @sub: the subexpression
7550 * Evaluates the expression resulting from @exp consuming a sub expression @sub
7551 * Based on algebraic derivation and sometimes direct Brzozowski derivation
7552 * it usually tatkes less than linear time and can handle expressions generating
7553 * infinite languages.
7555 * Returns the resulting expression or NULL in case of internal error, the
7556 * result must be freed
7559 xmlExpExpDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
7560 if ((exp == NULL) || (ctxt == NULL) || (sub == NULL))
7566 if (IS_NILLABLE(sub) && (!IS_NILLABLE(exp))) {
7568 printf("Sub nillable and not exp : can't subsume\n");
7570 return(forbiddenExp);
7572 if (xmlExpCheckCard(exp, sub) == 0) {
7574 printf("sub generate longuer sequances than exp : can't subsume\n");
7576 return(forbiddenExp);
7578 return(xmlExpExpDeriveInt(ctxt, exp, sub));
7583 * @ctxt: the expressions context
7584 * @exp: the englobing expression
7585 * @sub: the subexpression
7587 * Check whether @exp accepts all the languages accexpted by @sub
7588 * the input being a subexpression.
7590 * Returns 1 if true 0 if false and -1 in case of failure.
7593 xmlExpSubsume(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
7596 if ((exp == NULL) || (ctxt == NULL) || (sub == NULL))
7600 * TODO: speedup by checking the language of sub is a subset of the
7606 if (IS_NILLABLE(sub) && (!IS_NILLABLE(exp))) {
7608 printf("Sub nillable and not exp : can't subsume\n");
7612 if (xmlExpCheckCard(exp, sub) == 0) {
7614 printf("sub generate longuer sequances than exp : can't subsume\n");
7618 tmp = xmlExpExpDeriveInt(ctxt, exp, sub);
7620 printf("Result derivation :\n");
7625 if (tmp == forbiddenExp)
7627 if (tmp == emptyExp)
7629 if ((tmp != NULL) && (IS_NILLABLE(tmp))) {
7630 xmlExpFree(ctxt, tmp);
7633 xmlExpFree(ctxt, tmp);
7637 /************************************************************************
7639 * Parsing expression *
7641 ************************************************************************/
7643 static xmlExpNodePtr xmlExpParseExpr(xmlExpCtxtPtr ctxt);
7646 #define CUR (*ctxt->cur)
7648 #define NEXT ctxt->cur++;
7650 #define IS_BLANK(c) ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t'))
7651 #define SKIP_BLANKS while (IS_BLANK(*ctxt->cur)) ctxt->cur++;
7654 xmlExpParseNumber(xmlExpCtxtPtr ctxt) {
7662 if ((CUR < '0') || (CUR > '9'))
7664 while ((CUR >= '0') && (CUR <= '9')) {
7665 ret = ret * 10 + (CUR - '0');
7671 static xmlExpNodePtr
7672 xmlExpParseOr(xmlExpCtxtPtr ctxt) {
7679 if (*ctxt->cur == '(') {
7681 ret = xmlExpParseExpr(ctxt);
7683 if (*ctxt->cur != ')') {
7684 fprintf(stderr, "unbalanced '(' : %s\n", base);
7685 xmlExpFree(ctxt, ret);
7690 goto parse_quantifier;
7692 while ((CUR != 0) && (!(IS_BLANK(CUR))) && (CUR != '(') &&
7693 (CUR != ')') && (CUR != '|') && (CUR != ',') && (CUR != '{') &&
7694 (CUR != '*') && (CUR != '+') && (CUR != '?') && (CUR != '}'))
7696 val = xmlDictLookup(ctxt->dict, BAD_CAST base, ctxt->cur - base);
7699 ret = xmlExpHashGetEntry(ctxt, XML_EXP_ATOM, NULL, NULL, val, 0, 0);
7708 min = xmlExpParseNumber(ctxt);
7710 xmlExpFree(ctxt, ret);
7716 max = xmlExpParseNumber(ctxt);
7721 xmlExpFree(ctxt, ret);
7725 ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
7728 } else if (CUR == '?') {
7730 ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
7733 } else if (CUR == '+') {
7735 ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
7738 } else if (CUR == '*') {
7740 ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
7748 static xmlExpNodePtr
7749 xmlExpParseSeq(xmlExpCtxtPtr ctxt) {
7750 xmlExpNodePtr ret, right;
7752 ret = xmlExpParseOr(ctxt);
7754 while (CUR == '|') {
7756 right = xmlExpParseOr(ctxt);
7757 if (right == NULL) {
7758 xmlExpFree(ctxt, ret);
7761 ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, right, NULL, 0, 0);
7768 static xmlExpNodePtr
7769 xmlExpParseExpr(xmlExpCtxtPtr ctxt) {
7770 xmlExpNodePtr ret, right;
7772 ret = xmlExpParseSeq(ctxt);
7774 while (CUR == ',') {
7776 right = xmlExpParseSeq(ctxt);
7777 if (right == NULL) {
7778 xmlExpFree(ctxt, ret);
7781 ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, right, NULL, 0, 0);
7790 * @ctxt: the expressions context
7791 * @expr: the 0 terminated string
7793 * Minimal parser for regexps, it understand the following constructs
7794 * - string terminals
7795 * - choice operator |
7796 * - sequence operator ,
7797 * - subexpressions (...)
7798 * - usual cardinality operators + * and ?
7799 * - finite sequences { min, max }
7800 * - infinite sequences { min, * }
7801 * There is minimal checkings made especially no checking on strings values
7803 * Returns a new expression or NULL in case of failure
7806 xmlExpParse(xmlExpCtxtPtr ctxt, const char *expr) {
7812 ret = xmlExpParseExpr(ctxt);
7814 if (*ctxt->cur != 0) {
7815 xmlExpFree(ctxt, ret);
7822 xmlExpDumpInt(xmlBufferPtr buf, xmlExpNodePtr expr, int glob) {
7825 if (expr == NULL) return;
7826 if (glob) xmlBufferWriteChar(buf, "(");
7827 switch (expr->type) {
7829 xmlBufferWriteChar(buf, "empty");
7831 case XML_EXP_FORBID:
7832 xmlBufferWriteChar(buf, "forbidden");
7835 xmlBufferWriteCHAR(buf, expr->exp_str);
7839 if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
7840 xmlExpDumpInt(buf, c, 1);
7842 xmlExpDumpInt(buf, c, 0);
7843 xmlBufferWriteChar(buf, " , ");
7844 c = expr->exp_right;
7845 if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
7846 xmlExpDumpInt(buf, c, 1);
7848 xmlExpDumpInt(buf, c, 0);
7852 if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
7853 xmlExpDumpInt(buf, c, 1);
7855 xmlExpDumpInt(buf, c, 0);
7856 xmlBufferWriteChar(buf, " | ");
7857 c = expr->exp_right;
7858 if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
7859 xmlExpDumpInt(buf, c, 1);
7861 xmlExpDumpInt(buf, c, 0);
7863 case XML_EXP_COUNT: {
7867 if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
7868 xmlExpDumpInt(buf, c, 1);
7870 xmlExpDumpInt(buf, c, 0);
7871 if ((expr->exp_min == 0) && (expr->exp_max == 1)) {
7874 } else if ((expr->exp_min == 0) && (expr->exp_max == -1)) {
7877 } else if ((expr->exp_min == 1) && (expr->exp_max == -1)) {
7880 } else if (expr->exp_max == expr->exp_min) {
7881 snprintf(rep, 39, "{%d}", expr->exp_min);
7882 } else if (expr->exp_max < 0) {
7883 snprintf(rep, 39, "{%d,inf}", expr->exp_min);
7885 snprintf(rep, 39, "{%d,%d}", expr->exp_min, expr->exp_max);
7888 xmlBufferWriteChar(buf, rep);
7892 fprintf(stderr, "Error in tree\n");
7895 xmlBufferWriteChar(buf, ")");
7899 * @buf: a buffer to receive the output
7900 * @expr: the compiled expression
7902 * Serialize the expression as compiled to the buffer
7905 xmlExpDump(xmlBufferPtr buf, xmlExpNodePtr expr) {
7906 if ((buf == NULL) || (expr == NULL))
7908 xmlExpDumpInt(buf, expr, 0);
7913 * @expr: a compiled expression
7915 * Indicate the maximum number of input a expression can accept
7917 * Returns the maximum length or -1 in case of error
7920 xmlExpMaxToken(xmlExpNodePtr expr) {
7923 return(expr->c_max);
7927 * xmlExpCtxtNbNodes:
7928 * @ctxt: an expression context
7930 * Debugging facility provides the number of allocated nodes at a that point
7932 * Returns the number of nodes in use or -1 in case of error
7935 xmlExpCtxtNbNodes(xmlExpCtxtPtr ctxt) {
7938 return(ctxt->nb_nodes);
7943 * @ctxt: an expression context
7945 * Debugging facility provides the number of allocated nodes over lifetime
7947 * Returns the number of nodes ever allocated or -1 in case of error
7950 xmlExpCtxtNbCons(xmlExpCtxtPtr ctxt) {
7953 return(ctxt->nb_cons);
7956 #endif /* LIBXML_EXPR_ENABLED */
7957 #define bottom_xmlregexp
7958 #include "elfgcchack.h"
7959 #endif /* LIBXML_REGEXP_ENABLED */