Coverage Report

Created: 2023-06-07 06:54

/src/libxml2/xmlregexp.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * regexp.c: generic and extensible Regular Expression engine
3
 *
4
 * Basically designed with the purpose of compiling regexps for
5
 * the variety of validation/schemas 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
11
 *
12
 * See Copyright for the status of this software.
13
 *
14
 * Daniel Veillard <veillard@redhat.com>
15
 */
16
17
#define IN_LIBXML
18
#include "libxml.h"
19
20
#ifdef LIBXML_REGEXP_ENABLED
21
22
/* #define DEBUG_ERR */
23
24
#include <stdio.h>
25
#include <string.h>
26
#include <limits.h>
27
28
#include <libxml/tree.h>
29
#include <libxml/parserInternals.h>
30
#include <libxml/xmlregexp.h>
31
#include <libxml/xmlautomata.h>
32
#include <libxml/xmlunicode.h>
33
34
#include "private/error.h"
35
#include "private/regexp.h"
36
37
#ifndef SIZE_MAX
38
0
#define SIZE_MAX ((size_t) -1)
39
#endif
40
41
/* #define DEBUG_REGEXP_GRAPH */
42
/* #define DEBUG_REGEXP_EXEC */
43
/* #define DEBUG_PUSH */
44
/* #define DEBUG_COMPACTION */
45
46
0
#define MAX_PUSH 10000000
47
48
#ifdef ERROR
49
#undef ERROR
50
#endif
51
#define ERROR(str)              \
52
0
    ctxt->error = XML_REGEXP_COMPILE_ERROR;       \
53
0
    xmlRegexpErrCompile(ctxt, str);
54
0
#define NEXT ctxt->cur++
55
0
#define CUR (*(ctxt->cur))
56
0
#define NXT(index) (ctxt->cur[index])
57
58
0
#define CUR_SCHAR(s, l) xmlStringCurrentChar(NULL, s, &l)
59
0
#define NEXTL(l) ctxt->cur += l;
60
0
#define XML_REG_STRING_SEPARATOR '|'
61
/*
62
 * Need PREV to check on a '-' within a Character Group. May only be used
63
 * when it's guaranteed that cur is not at the beginning of ctxt->string!
64
 */
65
0
#define PREV (ctxt->cur[-1])
66
67
/**
68
 * TODO:
69
 *
70
 * macro to flag unimplemented blocks
71
 */
72
#define TODO                \
73
0
    xmlGenericError(xmlGenericErrorContext,       \
74
0
      "Unimplemented block at %s:%d\n",       \
75
0
            __FILE__, __LINE__);
76
77
/************************************************************************
78
 *                  *
79
 *      Datatypes and structures      *
80
 *                  *
81
 ************************************************************************/
82
83
/*
84
 * Note: the order of the enums below is significant, do not shuffle
85
 */
86
typedef enum {
87
    XML_REGEXP_EPSILON = 1,
88
    XML_REGEXP_CHARVAL,
89
    XML_REGEXP_RANGES,
90
    XML_REGEXP_SUBREG,  /* used for () sub regexps */
91
    XML_REGEXP_STRING,
92
    XML_REGEXP_ANYCHAR, /* . */
93
    XML_REGEXP_ANYSPACE, /* \s */
94
    XML_REGEXP_NOTSPACE, /* \S */
95
    XML_REGEXP_INITNAME, /* \l */
96
    XML_REGEXP_NOTINITNAME, /* \L */
97
    XML_REGEXP_NAMECHAR, /* \c */
98
    XML_REGEXP_NOTNAMECHAR, /* \C */
99
    XML_REGEXP_DECIMAL, /* \d */
100
    XML_REGEXP_NOTDECIMAL, /* \D */
101
    XML_REGEXP_REALCHAR, /* \w */
102
    XML_REGEXP_NOTREALCHAR, /* \W */
103
    XML_REGEXP_LETTER = 100,
104
    XML_REGEXP_LETTER_UPPERCASE,
105
    XML_REGEXP_LETTER_LOWERCASE,
106
    XML_REGEXP_LETTER_TITLECASE,
107
    XML_REGEXP_LETTER_MODIFIER,
108
    XML_REGEXP_LETTER_OTHERS,
109
    XML_REGEXP_MARK,
110
    XML_REGEXP_MARK_NONSPACING,
111
    XML_REGEXP_MARK_SPACECOMBINING,
112
    XML_REGEXP_MARK_ENCLOSING,
113
    XML_REGEXP_NUMBER,
114
    XML_REGEXP_NUMBER_DECIMAL,
115
    XML_REGEXP_NUMBER_LETTER,
116
    XML_REGEXP_NUMBER_OTHERS,
117
    XML_REGEXP_PUNCT,
118
    XML_REGEXP_PUNCT_CONNECTOR,
119
    XML_REGEXP_PUNCT_DASH,
120
    XML_REGEXP_PUNCT_OPEN,
121
    XML_REGEXP_PUNCT_CLOSE,
122
    XML_REGEXP_PUNCT_INITQUOTE,
123
    XML_REGEXP_PUNCT_FINQUOTE,
124
    XML_REGEXP_PUNCT_OTHERS,
125
    XML_REGEXP_SEPAR,
126
    XML_REGEXP_SEPAR_SPACE,
127
    XML_REGEXP_SEPAR_LINE,
128
    XML_REGEXP_SEPAR_PARA,
129
    XML_REGEXP_SYMBOL,
130
    XML_REGEXP_SYMBOL_MATH,
131
    XML_REGEXP_SYMBOL_CURRENCY,
132
    XML_REGEXP_SYMBOL_MODIFIER,
133
    XML_REGEXP_SYMBOL_OTHERS,
134
    XML_REGEXP_OTHER,
135
    XML_REGEXP_OTHER_CONTROL,
136
    XML_REGEXP_OTHER_FORMAT,
137
    XML_REGEXP_OTHER_PRIVATE,
138
    XML_REGEXP_OTHER_NA,
139
    XML_REGEXP_BLOCK_NAME
140
} xmlRegAtomType;
141
142
typedef enum {
143
    XML_REGEXP_QUANT_EPSILON = 1,
144
    XML_REGEXP_QUANT_ONCE,
145
    XML_REGEXP_QUANT_OPT,
146
    XML_REGEXP_QUANT_MULT,
147
    XML_REGEXP_QUANT_PLUS,
148
    XML_REGEXP_QUANT_ONCEONLY,
149
    XML_REGEXP_QUANT_ALL,
150
    XML_REGEXP_QUANT_RANGE
151
} xmlRegQuantType;
152
153
typedef enum {
154
    XML_REGEXP_START_STATE = 1,
155
    XML_REGEXP_FINAL_STATE,
156
    XML_REGEXP_TRANS_STATE,
157
    XML_REGEXP_SINK_STATE,
158
    XML_REGEXP_UNREACH_STATE
159
} xmlRegStateType;
160
161
typedef enum {
162
    XML_REGEXP_MARK_NORMAL = 0,
163
    XML_REGEXP_MARK_START,
164
    XML_REGEXP_MARK_VISITED
165
} xmlRegMarkedType;
166
167
typedef struct _xmlRegRange xmlRegRange;
168
typedef xmlRegRange *xmlRegRangePtr;
169
170
struct _xmlRegRange {
171
    int neg;    /* 0 normal, 1 not, 2 exclude */
172
    xmlRegAtomType type;
173
    int start;
174
    int end;
175
    xmlChar *blockName;
176
};
177
178
typedef struct _xmlRegAtom xmlRegAtom;
179
typedef xmlRegAtom *xmlRegAtomPtr;
180
181
typedef struct _xmlAutomataState xmlRegState;
182
typedef xmlRegState *xmlRegStatePtr;
183
184
struct _xmlRegAtom {
185
    int no;
186
    xmlRegAtomType type;
187
    xmlRegQuantType quant;
188
    int min;
189
    int max;
190
191
    void *valuep;
192
    void *valuep2;
193
    int neg;
194
    int codepoint;
195
    xmlRegStatePtr start;
196
    xmlRegStatePtr start0;
197
    xmlRegStatePtr stop;
198
    int maxRanges;
199
    int nbRanges;
200
    xmlRegRangePtr *ranges;
201
    void *data;
202
};
203
204
typedef struct _xmlRegCounter xmlRegCounter;
205
typedef xmlRegCounter *xmlRegCounterPtr;
206
207
struct _xmlRegCounter {
208
    int min;
209
    int max;
210
};
211
212
typedef struct _xmlRegTrans xmlRegTrans;
213
typedef xmlRegTrans *xmlRegTransPtr;
214
215
struct _xmlRegTrans {
216
    xmlRegAtomPtr atom;
217
    int to;
218
    int counter;
219
    int count;
220
    int nd;
221
};
222
223
struct _xmlAutomataState {
224
    xmlRegStateType type;
225
    xmlRegMarkedType mark;
226
    xmlRegMarkedType markd;
227
    xmlRegMarkedType reached;
228
    int no;
229
    int maxTrans;
230
    int nbTrans;
231
    xmlRegTrans *trans;
232
    /*  knowing states pointing to us can speed things up */
233
    int maxTransTo;
234
    int nbTransTo;
235
    int *transTo;
236
};
237
238
typedef struct _xmlAutomata xmlRegParserCtxt;
239
typedef xmlRegParserCtxt *xmlRegParserCtxtPtr;
240
241
0
#define AM_AUTOMATA_RNG 1
242
243
struct _xmlAutomata {
244
    xmlChar *string;
245
    xmlChar *cur;
246
247
    int error;
248
    int neg;
249
250
    xmlRegStatePtr start;
251
    xmlRegStatePtr end;
252
    xmlRegStatePtr state;
253
254
    xmlRegAtomPtr atom;
255
256
    int maxAtoms;
257
    int nbAtoms;
258
    xmlRegAtomPtr *atoms;
259
260
    int maxStates;
261
    int nbStates;
262
    xmlRegStatePtr *states;
263
264
    int maxCounters;
265
    int nbCounters;
266
    xmlRegCounter *counters;
267
268
    int determinist;
269
    int negs;
270
    int flags;
271
272
    int depth;
273
};
274
275
struct _xmlRegexp {
276
    xmlChar *string;
277
    int nbStates;
278
    xmlRegStatePtr *states;
279
    int nbAtoms;
280
    xmlRegAtomPtr *atoms;
281
    int nbCounters;
282
    xmlRegCounter *counters;
283
    int determinist;
284
    int flags;
285
    /*
286
     * That's the compact form for determinists automatas
287
     */
288
    int nbstates;
289
    int *compact;
290
    void **transdata;
291
    int nbstrings;
292
    xmlChar **stringMap;
293
};
294
295
typedef struct _xmlRegExecRollback xmlRegExecRollback;
296
typedef xmlRegExecRollback *xmlRegExecRollbackPtr;
297
298
struct _xmlRegExecRollback {
299
    xmlRegStatePtr state;/* the current state */
300
    int index;    /* the index in the input stack */
301
    int nextbranch; /* the next transition to explore in that state */
302
    int *counts;  /* save the automata state if it has some */
303
};
304
305
typedef struct _xmlRegInputToken xmlRegInputToken;
306
typedef xmlRegInputToken *xmlRegInputTokenPtr;
307
308
struct _xmlRegInputToken {
309
    xmlChar *value;
310
    void *data;
311
};
312
313
struct _xmlRegExecCtxt {
314
    int status;   /* execution status != 0 indicate an error */
315
    int determinist;  /* did we find an indeterministic behaviour */
316
    xmlRegexpPtr comp;  /* the compiled regexp */
317
    xmlRegExecCallbacks callback;
318
    void *data;
319
320
    xmlRegStatePtr state;/* the current state */
321
    int transno;  /* the current transition on that state */
322
    int transcount; /* the number of chars in char counted transitions */
323
324
    /*
325
     * A stack of rollback states
326
     */
327
    int maxRollbacks;
328
    int nbRollbacks;
329
    xmlRegExecRollback *rollbacks;
330
331
    /*
332
     * The state of the automata if any
333
     */
334
    int *counts;
335
336
    /*
337
     * The input stack
338
     */
339
    int inputStackMax;
340
    int inputStackNr;
341
    int index;
342
    int *charStack;
343
    const xmlChar *inputString; /* when operating on characters */
344
    xmlRegInputTokenPtr inputStack;/* when operating on strings */
345
346
    /*
347
     * error handling
348
     */
349
    int errStateNo;   /* the error state number */
350
    xmlRegStatePtr errState;    /* the error state */
351
    xmlChar *errString;   /* the string raising the error */
352
    int *errCounts;   /* counters at the error state */
353
    int nbPush;
354
};
355
356
0
#define REGEXP_ALL_COUNTER  0x123456
357
0
#define REGEXP_ALL_LAX_COUNTER  0x123457
358
359
static void xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top);
360
static void xmlRegFreeState(xmlRegStatePtr state);
361
static void xmlRegFreeAtom(xmlRegAtomPtr atom);
362
static int xmlRegStrEqualWildcard(const xmlChar *expStr, const xmlChar *valStr);
363
static int xmlRegCheckCharacter(xmlRegAtomPtr atom, int codepoint);
364
static int xmlRegCheckCharacterRange(xmlRegAtomType type, int codepoint,
365
                  int neg, int start, int end, const xmlChar *blockName);
366
367
/************************************************************************
368
 *                  *
369
 *    Regexp memory error handler       *
370
 *                  *
371
 ************************************************************************/
372
/**
373
 * xmlRegexpErrMemory:
374
 * @extra:  extra information
375
 *
376
 * Handle an out of memory condition
377
 */
378
static void
379
xmlRegexpErrMemory(xmlRegParserCtxtPtr ctxt, const char *extra)
380
0
{
381
0
    const char *regexp = NULL;
382
0
    if (ctxt != NULL) {
383
0
        regexp = (const char *) ctxt->string;
384
0
  ctxt->error = XML_ERR_NO_MEMORY;
385
0
    }
386
0
    __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_REGEXP,
387
0
        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
388
0
        regexp, NULL, 0, 0,
389
0
        "Memory allocation failed : %s\n", extra);
390
0
}
391
392
/**
393
 * xmlRegexpErrCompile:
394
 * @extra:  extra information
395
 *
396
 * Handle a compilation failure
397
 */
398
static void
399
xmlRegexpErrCompile(xmlRegParserCtxtPtr ctxt, const char *extra)
400
0
{
401
0
    const char *regexp = NULL;
402
0
    int idx = 0;
403
404
0
    if (ctxt != NULL) {
405
0
        regexp = (const char *) ctxt->string;
406
0
  idx = ctxt->cur - ctxt->string;
407
0
  ctxt->error = XML_REGEXP_COMPILE_ERROR;
408
0
    }
409
0
    __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_REGEXP,
410
0
        XML_REGEXP_COMPILE_ERROR, XML_ERR_FATAL, NULL, 0, extra,
411
0
        regexp, NULL, idx, 0,
412
0
        "failed to compile: %s\n", extra);
413
0
}
414
415
/************************************************************************
416
 *                  *
417
 *      Allocation/Deallocation       *
418
 *                  *
419
 ************************************************************************/
420
421
static int xmlFAComputesDeterminism(xmlRegParserCtxtPtr ctxt);
422
423
/**
424
 * xmlRegCalloc2:
425
 * @dim1:  size of first dimension
426
 * @dim2:  size of second dimension
427
 * @elemSize:  size of element
428
 *
429
 * Allocate a two-dimensional array and set all elements to zero.
430
 *
431
 * Returns the new array or NULL in case of error.
432
 */
433
static void*
434
0
xmlRegCalloc2(size_t dim1, size_t dim2, size_t elemSize) {
435
0
    size_t totalSize;
436
0
    void *ret;
437
438
    /* Check for overflow */
439
0
    if ((dim2 == 0) || (elemSize == 0) ||
440
0
        (dim1 > SIZE_MAX / dim2 / elemSize))
441
0
        return (NULL);
442
0
    totalSize = dim1 * dim2 * elemSize;
443
0
    ret = xmlMalloc(totalSize);
444
0
    if (ret != NULL)
445
0
        memset(ret, 0, totalSize);
446
0
    return (ret);
447
0
}
448
449
/**
450
 * xmlRegEpxFromParse:
451
 * @ctxt:  the parser context used to build it
452
 *
453
 * Allocate a new regexp and fill it with the result from the parser
454
 *
455
 * Returns the new regexp or NULL in case of error
456
 */
457
static xmlRegexpPtr
458
0
xmlRegEpxFromParse(xmlRegParserCtxtPtr ctxt) {
459
0
    xmlRegexpPtr ret;
460
461
0
    ret = (xmlRegexpPtr) xmlMalloc(sizeof(xmlRegexp));
462
0
    if (ret == NULL) {
463
0
  xmlRegexpErrMemory(ctxt, "compiling regexp");
464
0
  return(NULL);
465
0
    }
466
0
    memset(ret, 0, sizeof(xmlRegexp));
467
0
    ret->string = ctxt->string;
468
0
    ret->nbStates = ctxt->nbStates;
469
0
    ret->states = ctxt->states;
470
0
    ret->nbAtoms = ctxt->nbAtoms;
471
0
    ret->atoms = ctxt->atoms;
472
0
    ret->nbCounters = ctxt->nbCounters;
473
0
    ret->counters = ctxt->counters;
474
0
    ret->determinist = ctxt->determinist;
475
0
    ret->flags = ctxt->flags;
476
0
    if (ret->determinist == -1) {
477
0
        xmlRegexpIsDeterminist(ret);
478
0
    }
479
480
0
    if ((ret->determinist != 0) &&
481
0
  (ret->nbCounters == 0) &&
482
0
  (ctxt->negs == 0) &&
483
0
  (ret->atoms != NULL) &&
484
0
  (ret->atoms[0] != NULL) &&
485
0
  (ret->atoms[0]->type == XML_REGEXP_STRING)) {
486
0
  int i, j, nbstates = 0, nbatoms = 0;
487
0
  int *stateRemap;
488
0
  int *stringRemap;
489
0
  int *transitions;
490
0
  void **transdata;
491
0
  xmlChar **stringMap;
492
0
        xmlChar *value;
493
494
  /*
495
   * Switch to a compact representation
496
   * 1/ counting the effective number of states left
497
   * 2/ counting the unique number of atoms, and check that
498
   *    they are all of the string type
499
   * 3/ build a table state x atom for the transitions
500
   */
501
502
0
  stateRemap = xmlMalloc(ret->nbStates * sizeof(int));
503
0
  if (stateRemap == NULL) {
504
0
      xmlRegexpErrMemory(ctxt, "compiling regexp");
505
0
      xmlFree(ret);
506
0
      return(NULL);
507
0
  }
508
0
  for (i = 0;i < ret->nbStates;i++) {
509
0
      if (ret->states[i] != NULL) {
510
0
    stateRemap[i] = nbstates;
511
0
    nbstates++;
512
0
      } else {
513
0
    stateRemap[i] = -1;
514
0
      }
515
0
  }
516
#ifdef DEBUG_COMPACTION
517
  printf("Final: %d states\n", nbstates);
518
#endif
519
0
  stringMap = xmlMalloc(ret->nbAtoms * sizeof(char *));
520
0
  if (stringMap == NULL) {
521
0
      xmlRegexpErrMemory(ctxt, "compiling regexp");
522
0
      xmlFree(stateRemap);
523
0
      xmlFree(ret);
524
0
      return(NULL);
525
0
  }
526
0
  stringRemap = xmlMalloc(ret->nbAtoms * sizeof(int));
527
0
  if (stringRemap == NULL) {
528
0
      xmlRegexpErrMemory(ctxt, "compiling regexp");
529
0
      xmlFree(stringMap);
530
0
      xmlFree(stateRemap);
531
0
      xmlFree(ret);
532
0
      return(NULL);
533
0
  }
534
0
  for (i = 0;i < ret->nbAtoms;i++) {
535
0
      if ((ret->atoms[i]->type == XML_REGEXP_STRING) &&
536
0
    (ret->atoms[i]->quant == XML_REGEXP_QUANT_ONCE)) {
537
0
    value = ret->atoms[i]->valuep;
538
0
                for (j = 0;j < nbatoms;j++) {
539
0
        if (xmlStrEqual(stringMap[j], value)) {
540
0
      stringRemap[i] = j;
541
0
      break;
542
0
        }
543
0
    }
544
0
    if (j >= nbatoms) {
545
0
        stringRemap[i] = nbatoms;
546
0
        stringMap[nbatoms] = xmlStrdup(value);
547
0
        if (stringMap[nbatoms] == NULL) {
548
0
      for (i = 0;i < nbatoms;i++)
549
0
          xmlFree(stringMap[i]);
550
0
      xmlFree(stringRemap);
551
0
      xmlFree(stringMap);
552
0
      xmlFree(stateRemap);
553
0
      xmlFree(ret);
554
0
      return(NULL);
555
0
        }
556
0
        nbatoms++;
557
0
    }
558
0
      } else {
559
0
    xmlFree(stateRemap);
560
0
    xmlFree(stringRemap);
561
0
    for (i = 0;i < nbatoms;i++)
562
0
        xmlFree(stringMap[i]);
563
0
    xmlFree(stringMap);
564
0
    xmlFree(ret);
565
0
    return(NULL);
566
0
      }
567
0
  }
568
#ifdef DEBUG_COMPACTION
569
  printf("Final: %d atoms\n", nbatoms);
570
#endif
571
0
  transitions = (int *) xmlRegCalloc2(nbstates + 1, nbatoms + 1,
572
0
                                            sizeof(int));
573
0
  if (transitions == NULL) {
574
0
      xmlFree(stateRemap);
575
0
      xmlFree(stringRemap);
576
0
            for (i = 0;i < nbatoms;i++)
577
0
    xmlFree(stringMap[i]);
578
0
      xmlFree(stringMap);
579
0
      xmlFree(ret);
580
0
      return(NULL);
581
0
  }
582
583
  /*
584
   * Allocate the transition table. The first entry for each
585
   * state corresponds to the state type.
586
   */
587
0
  transdata = NULL;
588
589
0
  for (i = 0;i < ret->nbStates;i++) {
590
0
      int stateno, atomno, targetno, prev;
591
0
      xmlRegStatePtr state;
592
0
      xmlRegTransPtr trans;
593
594
0
      stateno = stateRemap[i];
595
0
      if (stateno == -1)
596
0
    continue;
597
0
      state = ret->states[i];
598
599
0
      transitions[stateno * (nbatoms + 1)] = state->type;
600
601
0
      for (j = 0;j < state->nbTrans;j++) {
602
0
    trans = &(state->trans[j]);
603
0
    if ((trans->to < 0) || (trans->atom == NULL))
604
0
        continue;
605
0
                atomno = stringRemap[trans->atom->no];
606
0
    if ((trans->atom->data != NULL) && (transdata == NULL)) {
607
0
        transdata = (void **) xmlRegCalloc2(nbstates, nbatoms,
608
0
                                      sizeof(void *));
609
0
        if (transdata == NULL) {
610
0
      xmlRegexpErrMemory(ctxt, "compiling regexp");
611
0
      break;
612
0
        }
613
0
    }
614
0
    targetno = stateRemap[trans->to];
615
    /*
616
     * if the same atom can generate transitions to 2 different
617
     * states then it means the automata is not deterministic and
618
     * the compact form can't be used !
619
     */
620
0
    prev = transitions[stateno * (nbatoms + 1) + atomno + 1];
621
0
    if (prev != 0) {
622
0
        if (prev != targetno + 1) {
623
0
      ret->determinist = 0;
624
#ifdef DEBUG_COMPACTION
625
      printf("Indet: state %d trans %d, atom %d to %d : %d to %d\n",
626
             i, j, trans->atom->no, trans->to, atomno, targetno);
627
      printf("       previous to is %d\n", prev);
628
#endif
629
0
      if (transdata != NULL)
630
0
          xmlFree(transdata);
631
0
      xmlFree(transitions);
632
0
      xmlFree(stateRemap);
633
0
      xmlFree(stringRemap);
634
0
      for (i = 0;i < nbatoms;i++)
635
0
          xmlFree(stringMap[i]);
636
0
      xmlFree(stringMap);
637
0
      goto not_determ;
638
0
        }
639
0
    } else {
640
#if 0
641
        printf("State %d trans %d: atom %d to %d : %d to %d\n",
642
         i, j, trans->atom->no, trans->to, atomno, targetno);
643
#endif
644
0
        transitions[stateno * (nbatoms + 1) + atomno + 1] =
645
0
      targetno + 1; /* to avoid 0 */
646
0
        if (transdata != NULL)
647
0
      transdata[stateno * nbatoms + atomno] =
648
0
          trans->atom->data;
649
0
    }
650
0
      }
651
0
  }
652
0
  ret->determinist = 1;
653
#ifdef DEBUG_COMPACTION
654
  /*
655
   * Debug
656
   */
657
  for (i = 0;i < nbstates;i++) {
658
      for (j = 0;j < nbatoms + 1;j++) {
659
                printf("%02d ", transitions[i * (nbatoms + 1) + j]);
660
      }
661
      printf("\n");
662
  }
663
  printf("\n");
664
#endif
665
  /*
666
   * Cleanup of the old data
667
   */
668
0
  if (ret->states != NULL) {
669
0
      for (i = 0;i < ret->nbStates;i++)
670
0
    xmlRegFreeState(ret->states[i]);
671
0
      xmlFree(ret->states);
672
0
  }
673
0
  ret->states = NULL;
674
0
  ret->nbStates = 0;
675
0
  if (ret->atoms != NULL) {
676
0
      for (i = 0;i < ret->nbAtoms;i++)
677
0
    xmlRegFreeAtom(ret->atoms[i]);
678
0
      xmlFree(ret->atoms);
679
0
  }
680
0
  ret->atoms = NULL;
681
0
  ret->nbAtoms = 0;
682
683
0
  ret->compact = transitions;
684
0
  ret->transdata = transdata;
685
0
  ret->stringMap = stringMap;
686
0
  ret->nbstrings = nbatoms;
687
0
  ret->nbstates = nbstates;
688
0
  xmlFree(stateRemap);
689
0
  xmlFree(stringRemap);
690
0
    }
691
0
not_determ:
692
0
    ctxt->string = NULL;
693
0
    ctxt->nbStates = 0;
694
0
    ctxt->states = NULL;
695
0
    ctxt->nbAtoms = 0;
696
0
    ctxt->atoms = NULL;
697
0
    ctxt->nbCounters = 0;
698
0
    ctxt->counters = NULL;
699
0
    return(ret);
700
0
}
701
702
/**
703
 * xmlRegNewParserCtxt:
704
 * @string:  the string to parse
705
 *
706
 * Allocate a new regexp parser context
707
 *
708
 * Returns the new context or NULL in case of error
709
 */
710
static xmlRegParserCtxtPtr
711
0
xmlRegNewParserCtxt(const xmlChar *string) {
712
0
    xmlRegParserCtxtPtr ret;
713
714
0
    ret = (xmlRegParserCtxtPtr) xmlMalloc(sizeof(xmlRegParserCtxt));
715
0
    if (ret == NULL)
716
0
  return(NULL);
717
0
    memset(ret, 0, sizeof(xmlRegParserCtxt));
718
0
    if (string != NULL)
719
0
  ret->string = xmlStrdup(string);
720
0
    ret->cur = ret->string;
721
0
    ret->neg = 0;
722
0
    ret->negs = 0;
723
0
    ret->error = 0;
724
0
    ret->determinist = -1;
725
0
    return(ret);
726
0
}
727
728
/**
729
 * xmlRegNewRange:
730
 * @ctxt:  the regexp parser context
731
 * @neg:  is that negative
732
 * @type:  the type of range
733
 * @start:  the start codepoint
734
 * @end:  the end codepoint
735
 *
736
 * Allocate a new regexp range
737
 *
738
 * Returns the new range or NULL in case of error
739
 */
740
static xmlRegRangePtr
741
xmlRegNewRange(xmlRegParserCtxtPtr ctxt,
742
0
         int neg, xmlRegAtomType type, int start, int end) {
743
0
    xmlRegRangePtr ret;
744
745
0
    ret = (xmlRegRangePtr) xmlMalloc(sizeof(xmlRegRange));
746
0
    if (ret == NULL) {
747
0
  xmlRegexpErrMemory(ctxt, "allocating range");
748
0
  return(NULL);
749
0
    }
750
0
    ret->neg = neg;
751
0
    ret->type = type;
752
0
    ret->start = start;
753
0
    ret->end = end;
754
0
    return(ret);
755
0
}
756
757
/**
758
 * xmlRegFreeRange:
759
 * @range:  the regexp range
760
 *
761
 * Free a regexp range
762
 */
763
static void
764
0
xmlRegFreeRange(xmlRegRangePtr range) {
765
0
    if (range == NULL)
766
0
  return;
767
768
0
    if (range->blockName != NULL)
769
0
  xmlFree(range->blockName);
770
0
    xmlFree(range);
771
0
}
772
773
/**
774
 * xmlRegCopyRange:
775
 * @range:  the regexp range
776
 *
777
 * Copy a regexp range
778
 *
779
 * Returns the new copy or NULL in case of error.
780
 */
781
static xmlRegRangePtr
782
0
xmlRegCopyRange(xmlRegParserCtxtPtr ctxt, xmlRegRangePtr range) {
783
0
    xmlRegRangePtr ret;
784
785
0
    if (range == NULL)
786
0
  return(NULL);
787
788
0
    ret = xmlRegNewRange(ctxt, range->neg, range->type, range->start,
789
0
                         range->end);
790
0
    if (ret == NULL)
791
0
        return(NULL);
792
0
    if (range->blockName != NULL) {
793
0
  ret->blockName = xmlStrdup(range->blockName);
794
0
  if (ret->blockName == NULL) {
795
0
      xmlRegexpErrMemory(ctxt, "allocating range");
796
0
      xmlRegFreeRange(ret);
797
0
      return(NULL);
798
0
  }
799
0
    }
800
0
    return(ret);
801
0
}
802
803
/**
804
 * xmlRegNewAtom:
805
 * @ctxt:  the regexp parser context
806
 * @type:  the type of atom
807
 *
808
 * Allocate a new atom
809
 *
810
 * Returns the new atom or NULL in case of error
811
 */
812
static xmlRegAtomPtr
813
0
xmlRegNewAtom(xmlRegParserCtxtPtr ctxt, xmlRegAtomType type) {
814
0
    xmlRegAtomPtr ret;
815
816
0
    ret = (xmlRegAtomPtr) xmlMalloc(sizeof(xmlRegAtom));
817
0
    if (ret == NULL) {
818
0
  xmlRegexpErrMemory(ctxt, "allocating atom");
819
0
  return(NULL);
820
0
    }
821
0
    memset(ret, 0, sizeof(xmlRegAtom));
822
0
    ret->type = type;
823
0
    ret->quant = XML_REGEXP_QUANT_ONCE;
824
0
    ret->min = 0;
825
0
    ret->max = 0;
826
0
    return(ret);
827
0
}
828
829
/**
830
 * xmlRegFreeAtom:
831
 * @atom:  the regexp atom
832
 *
833
 * Free a regexp atom
834
 */
835
static void
836
0
xmlRegFreeAtom(xmlRegAtomPtr atom) {
837
0
    int i;
838
839
0
    if (atom == NULL)
840
0
  return;
841
842
0
    for (i = 0;i < atom->nbRanges;i++)
843
0
  xmlRegFreeRange(atom->ranges[i]);
844
0
    if (atom->ranges != NULL)
845
0
  xmlFree(atom->ranges);
846
0
    if ((atom->type == XML_REGEXP_STRING) && (atom->valuep != NULL))
847
0
  xmlFree(atom->valuep);
848
0
    if ((atom->type == XML_REGEXP_STRING) && (atom->valuep2 != NULL))
849
0
  xmlFree(atom->valuep2);
850
0
    if ((atom->type == XML_REGEXP_BLOCK_NAME) && (atom->valuep != NULL))
851
0
  xmlFree(atom->valuep);
852
0
    xmlFree(atom);
853
0
}
854
855
/**
856
 * xmlRegCopyAtom:
857
 * @ctxt:  the regexp parser context
858
 * @atom:  the original atom
859
 *
860
 * Allocate a new regexp range
861
 *
862
 * Returns the new atom or NULL in case of error
863
 */
864
static xmlRegAtomPtr
865
0
xmlRegCopyAtom(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom) {
866
0
    xmlRegAtomPtr ret;
867
868
0
    ret = (xmlRegAtomPtr) xmlMalloc(sizeof(xmlRegAtom));
869
0
    if (ret == NULL) {
870
0
  xmlRegexpErrMemory(ctxt, "copying atom");
871
0
  return(NULL);
872
0
    }
873
0
    memset(ret, 0, sizeof(xmlRegAtom));
874
0
    ret->type = atom->type;
875
0
    ret->quant = atom->quant;
876
0
    ret->min = atom->min;
877
0
    ret->max = atom->max;
878
0
    if (atom->nbRanges > 0) {
879
0
        int i;
880
881
0
        ret->ranges = (xmlRegRangePtr *) xmlMalloc(sizeof(xmlRegRangePtr) *
882
0
                                             atom->nbRanges);
883
0
  if (ret->ranges == NULL) {
884
0
      xmlRegexpErrMemory(ctxt, "copying atom");
885
0
      goto error;
886
0
  }
887
0
  for (i = 0;i < atom->nbRanges;i++) {
888
0
      ret->ranges[i] = xmlRegCopyRange(ctxt, atom->ranges[i]);
889
0
      if (ret->ranges[i] == NULL)
890
0
          goto error;
891
0
      ret->nbRanges = i + 1;
892
0
  }
893
0
    }
894
0
    return(ret);
895
896
0
error:
897
0
    xmlRegFreeAtom(ret);
898
0
    return(NULL);
899
0
}
900
901
static xmlRegStatePtr
902
0
xmlRegNewState(xmlRegParserCtxtPtr ctxt) {
903
0
    xmlRegStatePtr ret;
904
905
0
    ret = (xmlRegStatePtr) xmlMalloc(sizeof(xmlRegState));
906
0
    if (ret == NULL) {
907
0
  xmlRegexpErrMemory(ctxt, "allocating state");
908
0
  return(NULL);
909
0
    }
910
0
    memset(ret, 0, sizeof(xmlRegState));
911
0
    ret->type = XML_REGEXP_TRANS_STATE;
912
0
    ret->mark = XML_REGEXP_MARK_NORMAL;
913
0
    return(ret);
914
0
}
915
916
/**
917
 * xmlRegFreeState:
918
 * @state:  the regexp state
919
 *
920
 * Free a regexp state
921
 */
922
static void
923
0
xmlRegFreeState(xmlRegStatePtr state) {
924
0
    if (state == NULL)
925
0
  return;
926
927
0
    if (state->trans != NULL)
928
0
  xmlFree(state->trans);
929
0
    if (state->transTo != NULL)
930
0
  xmlFree(state->transTo);
931
0
    xmlFree(state);
932
0
}
933
934
/**
935
 * xmlRegFreeParserCtxt:
936
 * @ctxt:  the regexp parser context
937
 *
938
 * Free a regexp parser context
939
 */
940
static void
941
0
xmlRegFreeParserCtxt(xmlRegParserCtxtPtr ctxt) {
942
0
    int i;
943
0
    if (ctxt == NULL)
944
0
  return;
945
946
0
    if (ctxt->string != NULL)
947
0
  xmlFree(ctxt->string);
948
0
    if (ctxt->states != NULL) {
949
0
  for (i = 0;i < ctxt->nbStates;i++)
950
0
      xmlRegFreeState(ctxt->states[i]);
951
0
  xmlFree(ctxt->states);
952
0
    }
953
0
    if (ctxt->atoms != NULL) {
954
0
  for (i = 0;i < ctxt->nbAtoms;i++)
955
0
      xmlRegFreeAtom(ctxt->atoms[i]);
956
0
  xmlFree(ctxt->atoms);
957
0
    }
958
0
    if (ctxt->counters != NULL)
959
0
  xmlFree(ctxt->counters);
960
0
    xmlFree(ctxt);
961
0
}
962
963
/************************************************************************
964
 *                  *
965
 *      Display of Data structures      *
966
 *                  *
967
 ************************************************************************/
968
969
static void
970
0
xmlRegPrintAtomType(FILE *output, xmlRegAtomType type) {
971
0
    switch (type) {
972
0
        case XML_REGEXP_EPSILON:
973
0
      fprintf(output, "epsilon "); break;
974
0
        case XML_REGEXP_CHARVAL:
975
0
      fprintf(output, "charval "); break;
976
0
        case XML_REGEXP_RANGES:
977
0
      fprintf(output, "ranges "); break;
978
0
        case XML_REGEXP_SUBREG:
979
0
      fprintf(output, "subexpr "); break;
980
0
        case XML_REGEXP_STRING:
981
0
      fprintf(output, "string "); break;
982
0
        case XML_REGEXP_ANYCHAR:
983
0
      fprintf(output, "anychar "); break;
984
0
        case XML_REGEXP_ANYSPACE:
985
0
      fprintf(output, "anyspace "); break;
986
0
        case XML_REGEXP_NOTSPACE:
987
0
      fprintf(output, "notspace "); break;
988
0
        case XML_REGEXP_INITNAME:
989
0
      fprintf(output, "initname "); break;
990
0
        case XML_REGEXP_NOTINITNAME:
991
0
      fprintf(output, "notinitname "); break;
992
0
        case XML_REGEXP_NAMECHAR:
993
0
      fprintf(output, "namechar "); break;
994
0
        case XML_REGEXP_NOTNAMECHAR:
995
0
      fprintf(output, "notnamechar "); break;
996
0
        case XML_REGEXP_DECIMAL:
997
0
      fprintf(output, "decimal "); break;
998
0
        case XML_REGEXP_NOTDECIMAL:
999
0
      fprintf(output, "notdecimal "); break;
1000
0
        case XML_REGEXP_REALCHAR:
1001
0
      fprintf(output, "realchar "); break;
1002
0
        case XML_REGEXP_NOTREALCHAR:
1003
0
      fprintf(output, "notrealchar "); break;
1004
0
        case XML_REGEXP_LETTER:
1005
0
            fprintf(output, "LETTER "); break;
1006
0
        case XML_REGEXP_LETTER_UPPERCASE:
1007
0
            fprintf(output, "LETTER_UPPERCASE "); break;
1008
0
        case XML_REGEXP_LETTER_LOWERCASE:
1009
0
            fprintf(output, "LETTER_LOWERCASE "); break;
1010
0
        case XML_REGEXP_LETTER_TITLECASE:
1011
0
            fprintf(output, "LETTER_TITLECASE "); break;
1012
0
        case XML_REGEXP_LETTER_MODIFIER:
1013
0
            fprintf(output, "LETTER_MODIFIER "); break;
1014
0
        case XML_REGEXP_LETTER_OTHERS:
1015
0
            fprintf(output, "LETTER_OTHERS "); break;
1016
0
        case XML_REGEXP_MARK:
1017
0
            fprintf(output, "MARK "); break;
1018
0
        case XML_REGEXP_MARK_NONSPACING:
1019
0
            fprintf(output, "MARK_NONSPACING "); break;
1020
0
        case XML_REGEXP_MARK_SPACECOMBINING:
1021
0
            fprintf(output, "MARK_SPACECOMBINING "); break;
1022
0
        case XML_REGEXP_MARK_ENCLOSING:
1023
0
            fprintf(output, "MARK_ENCLOSING "); break;
1024
0
        case XML_REGEXP_NUMBER:
1025
0
            fprintf(output, "NUMBER "); break;
1026
0
        case XML_REGEXP_NUMBER_DECIMAL:
1027
0
            fprintf(output, "NUMBER_DECIMAL "); break;
1028
0
        case XML_REGEXP_NUMBER_LETTER:
1029
0
            fprintf(output, "NUMBER_LETTER "); break;
1030
0
        case XML_REGEXP_NUMBER_OTHERS:
1031
0
            fprintf(output, "NUMBER_OTHERS "); break;
1032
0
        case XML_REGEXP_PUNCT:
1033
0
            fprintf(output, "PUNCT "); break;
1034
0
        case XML_REGEXP_PUNCT_CONNECTOR:
1035
0
            fprintf(output, "PUNCT_CONNECTOR "); break;
1036
0
        case XML_REGEXP_PUNCT_DASH:
1037
0
            fprintf(output, "PUNCT_DASH "); break;
1038
0
        case XML_REGEXP_PUNCT_OPEN:
1039
0
            fprintf(output, "PUNCT_OPEN "); break;
1040
0
        case XML_REGEXP_PUNCT_CLOSE:
1041
0
            fprintf(output, "PUNCT_CLOSE "); break;
1042
0
        case XML_REGEXP_PUNCT_INITQUOTE:
1043
0
            fprintf(output, "PUNCT_INITQUOTE "); break;
1044
0
        case XML_REGEXP_PUNCT_FINQUOTE:
1045
0
            fprintf(output, "PUNCT_FINQUOTE "); break;
1046
0
        case XML_REGEXP_PUNCT_OTHERS:
1047
0
            fprintf(output, "PUNCT_OTHERS "); break;
1048
0
        case XML_REGEXP_SEPAR:
1049
0
            fprintf(output, "SEPAR "); break;
1050
0
        case XML_REGEXP_SEPAR_SPACE:
1051
0
            fprintf(output, "SEPAR_SPACE "); break;
1052
0
        case XML_REGEXP_SEPAR_LINE:
1053
0
            fprintf(output, "SEPAR_LINE "); break;
1054
0
        case XML_REGEXP_SEPAR_PARA:
1055
0
            fprintf(output, "SEPAR_PARA "); break;
1056
0
        case XML_REGEXP_SYMBOL:
1057
0
            fprintf(output, "SYMBOL "); break;
1058
0
        case XML_REGEXP_SYMBOL_MATH:
1059
0
            fprintf(output, "SYMBOL_MATH "); break;
1060
0
        case XML_REGEXP_SYMBOL_CURRENCY:
1061
0
            fprintf(output, "SYMBOL_CURRENCY "); break;
1062
0
        case XML_REGEXP_SYMBOL_MODIFIER:
1063
0
            fprintf(output, "SYMBOL_MODIFIER "); break;
1064
0
        case XML_REGEXP_SYMBOL_OTHERS:
1065
0
            fprintf(output, "SYMBOL_OTHERS "); break;
1066
0
        case XML_REGEXP_OTHER:
1067
0
            fprintf(output, "OTHER "); break;
1068
0
        case XML_REGEXP_OTHER_CONTROL:
1069
0
            fprintf(output, "OTHER_CONTROL "); break;
1070
0
        case XML_REGEXP_OTHER_FORMAT:
1071
0
            fprintf(output, "OTHER_FORMAT "); break;
1072
0
        case XML_REGEXP_OTHER_PRIVATE:
1073
0
            fprintf(output, "OTHER_PRIVATE "); break;
1074
0
        case XML_REGEXP_OTHER_NA:
1075
0
            fprintf(output, "OTHER_NA "); break;
1076
0
        case XML_REGEXP_BLOCK_NAME:
1077
0
      fprintf(output, "BLOCK "); break;
1078
0
    }
1079
0
}
1080
1081
static void
1082
0
xmlRegPrintQuantType(FILE *output, xmlRegQuantType type) {
1083
0
    switch (type) {
1084
0
        case XML_REGEXP_QUANT_EPSILON:
1085
0
      fprintf(output, "epsilon "); break;
1086
0
        case XML_REGEXP_QUANT_ONCE:
1087
0
      fprintf(output, "once "); break;
1088
0
        case XML_REGEXP_QUANT_OPT:
1089
0
      fprintf(output, "? "); break;
1090
0
        case XML_REGEXP_QUANT_MULT:
1091
0
      fprintf(output, "* "); break;
1092
0
        case XML_REGEXP_QUANT_PLUS:
1093
0
      fprintf(output, "+ "); break;
1094
0
  case XML_REGEXP_QUANT_RANGE:
1095
0
      fprintf(output, "range "); break;
1096
0
  case XML_REGEXP_QUANT_ONCEONLY:
1097
0
      fprintf(output, "onceonly "); break;
1098
0
  case XML_REGEXP_QUANT_ALL:
1099
0
      fprintf(output, "all "); break;
1100
0
    }
1101
0
}
1102
static void
1103
0
xmlRegPrintRange(FILE *output, xmlRegRangePtr range) {
1104
0
    fprintf(output, "  range: ");
1105
0
    if (range->neg)
1106
0
  fprintf(output, "negative ");
1107
0
    xmlRegPrintAtomType(output, range->type);
1108
0
    fprintf(output, "%c - %c\n", range->start, range->end);
1109
0
}
1110
1111
static void
1112
0
xmlRegPrintAtom(FILE *output, xmlRegAtomPtr atom) {
1113
0
    fprintf(output, " atom: ");
1114
0
    if (atom == NULL) {
1115
0
  fprintf(output, "NULL\n");
1116
0
  return;
1117
0
    }
1118
0
    if (atom->neg)
1119
0
        fprintf(output, "not ");
1120
0
    xmlRegPrintAtomType(output, atom->type);
1121
0
    xmlRegPrintQuantType(output, atom->quant);
1122
0
    if (atom->quant == XML_REGEXP_QUANT_RANGE)
1123
0
  fprintf(output, "%d-%d ", atom->min, atom->max);
1124
0
    if (atom->type == XML_REGEXP_STRING)
1125
0
  fprintf(output, "'%s' ", (char *) atom->valuep);
1126
0
    if (atom->type == XML_REGEXP_CHARVAL)
1127
0
  fprintf(output, "char %c\n", atom->codepoint);
1128
0
    else if (atom->type == XML_REGEXP_RANGES) {
1129
0
  int i;
1130
0
  fprintf(output, "%d entries\n", atom->nbRanges);
1131
0
  for (i = 0; i < atom->nbRanges;i++)
1132
0
      xmlRegPrintRange(output, atom->ranges[i]);
1133
0
    } else if (atom->type == XML_REGEXP_SUBREG) {
1134
0
  fprintf(output, "start %d end %d\n", atom->start->no, atom->stop->no);
1135
0
    } else {
1136
0
  fprintf(output, "\n");
1137
0
    }
1138
0
}
1139
1140
static void
1141
0
xmlRegPrintTrans(FILE *output, xmlRegTransPtr trans) {
1142
0
    fprintf(output, "  trans: ");
1143
0
    if (trans == NULL) {
1144
0
  fprintf(output, "NULL\n");
1145
0
  return;
1146
0
    }
1147
0
    if (trans->to < 0) {
1148
0
  fprintf(output, "removed\n");
1149
0
  return;
1150
0
    }
1151
0
    if (trans->nd != 0) {
1152
0
  if (trans->nd == 2)
1153
0
      fprintf(output, "last not determinist, ");
1154
0
  else
1155
0
      fprintf(output, "not determinist, ");
1156
0
    }
1157
0
    if (trans->counter >= 0) {
1158
0
  fprintf(output, "counted %d, ", trans->counter);
1159
0
    }
1160
0
    if (trans->count == REGEXP_ALL_COUNTER) {
1161
0
  fprintf(output, "all transition, ");
1162
0
    } else if (trans->count >= 0) {
1163
0
  fprintf(output, "count based %d, ", trans->count);
1164
0
    }
1165
0
    if (trans->atom == NULL) {
1166
0
  fprintf(output, "epsilon to %d\n", trans->to);
1167
0
  return;
1168
0
    }
1169
0
    if (trans->atom->type == XML_REGEXP_CHARVAL)
1170
0
  fprintf(output, "char %c ", trans->atom->codepoint);
1171
0
    fprintf(output, "atom %d, to %d\n", trans->atom->no, trans->to);
1172
0
}
1173
1174
static void
1175
0
xmlRegPrintState(FILE *output, xmlRegStatePtr state) {
1176
0
    int i;
1177
1178
0
    fprintf(output, " state: ");
1179
0
    if (state == NULL) {
1180
0
  fprintf(output, "NULL\n");
1181
0
  return;
1182
0
    }
1183
0
    if (state->type == XML_REGEXP_START_STATE)
1184
0
  fprintf(output, "START ");
1185
0
    if (state->type == XML_REGEXP_FINAL_STATE)
1186
0
  fprintf(output, "FINAL ");
1187
1188
0
    fprintf(output, "%d, %d transitions:\n", state->no, state->nbTrans);
1189
0
    for (i = 0;i < state->nbTrans; i++) {
1190
0
  xmlRegPrintTrans(output, &(state->trans[i]));
1191
0
    }
1192
0
}
1193
1194
#ifdef DEBUG_REGEXP_GRAPH
1195
static void
1196
xmlRegPrintCtxt(FILE *output, xmlRegParserCtxtPtr ctxt) {
1197
    int i;
1198
1199
    fprintf(output, " ctxt: ");
1200
    if (ctxt == NULL) {
1201
  fprintf(output, "NULL\n");
1202
  return;
1203
    }
1204
    fprintf(output, "'%s' ", ctxt->string);
1205
    if (ctxt->error)
1206
  fprintf(output, "error ");
1207
    if (ctxt->neg)
1208
  fprintf(output, "neg ");
1209
    fprintf(output, "\n");
1210
    fprintf(output, "%d atoms:\n", ctxt->nbAtoms);
1211
    for (i = 0;i < ctxt->nbAtoms; i++) {
1212
  fprintf(output, " %02d ", i);
1213
  xmlRegPrintAtom(output, ctxt->atoms[i]);
1214
    }
1215
    if (ctxt->atom != NULL) {
1216
  fprintf(output, "current atom:\n");
1217
  xmlRegPrintAtom(output, ctxt->atom);
1218
    }
1219
    fprintf(output, "%d states:", ctxt->nbStates);
1220
    if (ctxt->start != NULL)
1221
  fprintf(output, " start: %d", ctxt->start->no);
1222
    if (ctxt->end != NULL)
1223
  fprintf(output, " end: %d", ctxt->end->no);
1224
    fprintf(output, "\n");
1225
    for (i = 0;i < ctxt->nbStates; i++) {
1226
  xmlRegPrintState(output, ctxt->states[i]);
1227
    }
1228
    fprintf(output, "%d counters:\n", ctxt->nbCounters);
1229
    for (i = 0;i < ctxt->nbCounters; i++) {
1230
  fprintf(output, " %d: min %d max %d\n", i, ctxt->counters[i].min,
1231
                                    ctxt->counters[i].max);
1232
    }
1233
}
1234
#endif
1235
1236
/************************************************************************
1237
 *                  *
1238
 *     Finite Automata structures manipulations   *
1239
 *                  *
1240
 ************************************************************************/
1241
1242
static xmlRegRangePtr
1243
xmlRegAtomAddRange(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom,
1244
             int neg, xmlRegAtomType type, int start, int end,
1245
0
       xmlChar *blockName) {
1246
0
    xmlRegRangePtr range;
1247
1248
0
    if (atom == NULL) {
1249
0
  ERROR("add range: atom is NULL");
1250
0
  return(NULL);
1251
0
    }
1252
0
    if (atom->type != XML_REGEXP_RANGES) {
1253
0
  ERROR("add range: atom is not ranges");
1254
0
  return(NULL);
1255
0
    }
1256
0
    if (atom->maxRanges == 0) {
1257
0
  atom->maxRanges = 4;
1258
0
  atom->ranges = (xmlRegRangePtr *) xmlMalloc(atom->maxRanges *
1259
0
                                 sizeof(xmlRegRangePtr));
1260
0
  if (atom->ranges == NULL) {
1261
0
      xmlRegexpErrMemory(ctxt, "adding ranges");
1262
0
      atom->maxRanges = 0;
1263
0
      return(NULL);
1264
0
  }
1265
0
    } else if (atom->nbRanges >= atom->maxRanges) {
1266
0
  xmlRegRangePtr *tmp;
1267
0
  atom->maxRanges *= 2;
1268
0
  tmp = (xmlRegRangePtr *) xmlRealloc(atom->ranges, atom->maxRanges *
1269
0
                                 sizeof(xmlRegRangePtr));
1270
0
  if (tmp == NULL) {
1271
0
      xmlRegexpErrMemory(ctxt, "adding ranges");
1272
0
      atom->maxRanges /= 2;
1273
0
      return(NULL);
1274
0
  }
1275
0
  atom->ranges = tmp;
1276
0
    }
1277
0
    range = xmlRegNewRange(ctxt, neg, type, start, end);
1278
0
    if (range == NULL)
1279
0
  return(NULL);
1280
0
    range->blockName = blockName;
1281
0
    atom->ranges[atom->nbRanges++] = range;
1282
1283
0
    return(range);
1284
0
}
1285
1286
static int
1287
0
xmlRegGetCounter(xmlRegParserCtxtPtr ctxt) {
1288
0
    if (ctxt->maxCounters == 0) {
1289
0
  ctxt->maxCounters = 4;
1290
0
  ctxt->counters = (xmlRegCounter *) xmlMalloc(ctxt->maxCounters *
1291
0
                                 sizeof(xmlRegCounter));
1292
0
  if (ctxt->counters == NULL) {
1293
0
      xmlRegexpErrMemory(ctxt, "allocating counter");
1294
0
      ctxt->maxCounters = 0;
1295
0
      return(-1);
1296
0
  }
1297
0
    } else if (ctxt->nbCounters >= ctxt->maxCounters) {
1298
0
  xmlRegCounter *tmp;
1299
0
  ctxt->maxCounters *= 2;
1300
0
  tmp = (xmlRegCounter *) xmlRealloc(ctxt->counters, ctxt->maxCounters *
1301
0
                               sizeof(xmlRegCounter));
1302
0
  if (tmp == NULL) {
1303
0
      xmlRegexpErrMemory(ctxt, "allocating counter");
1304
0
      ctxt->maxCounters /= 2;
1305
0
      return(-1);
1306
0
  }
1307
0
  ctxt->counters = tmp;
1308
0
    }
1309
0
    ctxt->counters[ctxt->nbCounters].min = -1;
1310
0
    ctxt->counters[ctxt->nbCounters].max = -1;
1311
0
    return(ctxt->nbCounters++);
1312
0
}
1313
1314
static int
1315
0
xmlRegAtomPush(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom) {
1316
0
    if (atom == NULL) {
1317
0
  ERROR("atom push: atom is NULL");
1318
0
  return(-1);
1319
0
    }
1320
0
    if (ctxt->nbAtoms >= ctxt->maxAtoms) {
1321
0
        size_t newSize = ctxt->maxAtoms ? ctxt->maxAtoms * 2 : 4;
1322
0
  xmlRegAtomPtr *tmp;
1323
1324
0
  tmp = xmlRealloc(ctxt->atoms, newSize * sizeof(xmlRegAtomPtr));
1325
0
  if (tmp == NULL) {
1326
0
      xmlRegexpErrMemory(ctxt, "allocating counter");
1327
0
      return(-1);
1328
0
  }
1329
0
  ctxt->atoms = tmp;
1330
0
        ctxt->maxAtoms = newSize;
1331
0
    }
1332
0
    atom->no = ctxt->nbAtoms;
1333
0
    ctxt->atoms[ctxt->nbAtoms++] = atom;
1334
0
    return(0);
1335
0
}
1336
1337
static void
1338
xmlRegStateAddTransTo(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr target,
1339
0
                      int from) {
1340
0
    if (target->maxTransTo == 0) {
1341
0
  target->maxTransTo = 8;
1342
0
  target->transTo = (int *) xmlMalloc(target->maxTransTo *
1343
0
                                 sizeof(int));
1344
0
  if (target->transTo == NULL) {
1345
0
      xmlRegexpErrMemory(ctxt, "adding transition");
1346
0
      target->maxTransTo = 0;
1347
0
      return;
1348
0
  }
1349
0
    } else if (target->nbTransTo >= target->maxTransTo) {
1350
0
  int *tmp;
1351
0
  target->maxTransTo *= 2;
1352
0
  tmp = (int *) xmlRealloc(target->transTo, target->maxTransTo *
1353
0
                                 sizeof(int));
1354
0
  if (tmp == NULL) {
1355
0
      xmlRegexpErrMemory(ctxt, "adding transition");
1356
0
      target->maxTransTo /= 2;
1357
0
      return;
1358
0
  }
1359
0
  target->transTo = tmp;
1360
0
    }
1361
0
    target->transTo[target->nbTransTo] = from;
1362
0
    target->nbTransTo++;
1363
0
}
1364
1365
static void
1366
xmlRegStateAddTrans(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state,
1367
              xmlRegAtomPtr atom, xmlRegStatePtr target,
1368
0
        int counter, int count) {
1369
1370
0
    int nrtrans;
1371
1372
0
    if (state == NULL) {
1373
0
  ERROR("add state: state is NULL");
1374
0
  return;
1375
0
    }
1376
0
    if (target == NULL) {
1377
0
  ERROR("add state: target is NULL");
1378
0
  return;
1379
0
    }
1380
    /*
1381
     * Other routines follow the philosophy 'When in doubt, add a transition'
1382
     * so we check here whether such a transition is already present and, if
1383
     * so, silently ignore this request.
1384
     */
1385
1386
0
    for (nrtrans = state->nbTrans - 1; nrtrans >= 0; nrtrans--) {
1387
0
  xmlRegTransPtr trans = &(state->trans[nrtrans]);
1388
0
  if ((trans->atom == atom) &&
1389
0
      (trans->to == target->no) &&
1390
0
      (trans->counter == counter) &&
1391
0
      (trans->count == count)) {
1392
#ifdef DEBUG_REGEXP_GRAPH
1393
      printf("Ignoring duplicate transition from %d to %d\n",
1394
        state->no, target->no);
1395
#endif
1396
0
      return;
1397
0
  }
1398
0
    }
1399
1400
0
    if (state->maxTrans == 0) {
1401
0
  state->maxTrans = 8;
1402
0
  state->trans = (xmlRegTrans *) xmlMalloc(state->maxTrans *
1403
0
                                 sizeof(xmlRegTrans));
1404
0
  if (state->trans == NULL) {
1405
0
      xmlRegexpErrMemory(ctxt, "adding transition");
1406
0
      state->maxTrans = 0;
1407
0
      return;
1408
0
  }
1409
0
    } else if (state->nbTrans >= state->maxTrans) {
1410
0
  xmlRegTrans *tmp;
1411
0
  state->maxTrans *= 2;
1412
0
  tmp = (xmlRegTrans *) xmlRealloc(state->trans, state->maxTrans *
1413
0
                                 sizeof(xmlRegTrans));
1414
0
  if (tmp == NULL) {
1415
0
      xmlRegexpErrMemory(ctxt, "adding transition");
1416
0
      state->maxTrans /= 2;
1417
0
      return;
1418
0
  }
1419
0
  state->trans = tmp;
1420
0
    }
1421
#ifdef DEBUG_REGEXP_GRAPH
1422
    printf("Add trans from %d to %d ", state->no, target->no);
1423
    if (count == REGEXP_ALL_COUNTER)
1424
  printf("all transition\n");
1425
    else if (count >= 0)
1426
  printf("count based %d\n", count);
1427
    else if (counter >= 0)
1428
  printf("counted %d\n", counter);
1429
    else if (atom == NULL)
1430
  printf("epsilon transition\n");
1431
    else if (atom != NULL)
1432
        xmlRegPrintAtom(stdout, atom);
1433
#endif
1434
1435
0
    state->trans[state->nbTrans].atom = atom;
1436
0
    state->trans[state->nbTrans].to = target->no;
1437
0
    state->trans[state->nbTrans].counter = counter;
1438
0
    state->trans[state->nbTrans].count = count;
1439
0
    state->trans[state->nbTrans].nd = 0;
1440
0
    state->nbTrans++;
1441
0
    xmlRegStateAddTransTo(ctxt, target, state->no);
1442
0
}
1443
1444
static xmlRegStatePtr
1445
0
xmlRegStatePush(xmlRegParserCtxtPtr ctxt) {
1446
0
    xmlRegStatePtr state;
1447
1448
0
    if (ctxt->nbStates >= ctxt->maxStates) {
1449
0
        size_t newSize = ctxt->maxStates ? ctxt->maxStates * 2 : 4;
1450
0
  xmlRegStatePtr *tmp;
1451
1452
0
  tmp = xmlRealloc(ctxt->states, newSize * sizeof(tmp[0]));
1453
0
  if (tmp == NULL) {
1454
0
      xmlRegexpErrMemory(ctxt, "adding state");
1455
0
      return(NULL);
1456
0
  }
1457
0
  ctxt->states = tmp;
1458
0
  ctxt->maxStates = newSize;
1459
0
    }
1460
1461
0
    state = xmlRegNewState(ctxt);
1462
0
    if (state == NULL)
1463
0
        return(NULL);
1464
1465
0
    state->no = ctxt->nbStates;
1466
0
    ctxt->states[ctxt->nbStates++] = state;
1467
1468
0
    return(state);
1469
0
}
1470
1471
/**
1472
 * xmlFAGenerateAllTransition:
1473
 * @ctxt:  a regexp parser context
1474
 * @from:  the from state
1475
 * @to:  the target state or NULL for building a new one
1476
 * @lax:
1477
 *
1478
 */
1479
static int
1480
xmlFAGenerateAllTransition(xmlRegParserCtxtPtr ctxt,
1481
         xmlRegStatePtr from, xmlRegStatePtr to,
1482
0
         int lax) {
1483
0
    if (to == NULL) {
1484
0
  to = xmlRegStatePush(ctxt);
1485
0
        if (to == NULL)
1486
0
            return(-1);
1487
0
  ctxt->state = to;
1488
0
    }
1489
0
    if (lax)
1490
0
  xmlRegStateAddTrans(ctxt, from, NULL, to, -1, REGEXP_ALL_LAX_COUNTER);
1491
0
    else
1492
0
  xmlRegStateAddTrans(ctxt, from, NULL, to, -1, REGEXP_ALL_COUNTER);
1493
0
    return(0);
1494
0
}
1495
1496
/**
1497
 * xmlFAGenerateEpsilonTransition:
1498
 * @ctxt:  a regexp parser context
1499
 * @from:  the from state
1500
 * @to:  the target state or NULL for building a new one
1501
 *
1502
 */
1503
static int
1504
xmlFAGenerateEpsilonTransition(xmlRegParserCtxtPtr ctxt,
1505
0
             xmlRegStatePtr from, xmlRegStatePtr to) {
1506
0
    if (to == NULL) {
1507
0
  to = xmlRegStatePush(ctxt);
1508
0
        if (to == NULL)
1509
0
            return(-1);
1510
0
  ctxt->state = to;
1511
0
    }
1512
0
    xmlRegStateAddTrans(ctxt, from, NULL, to, -1, -1);
1513
0
    return(0);
1514
0
}
1515
1516
/**
1517
 * xmlFAGenerateCountedEpsilonTransition:
1518
 * @ctxt:  a regexp parser context
1519
 * @from:  the from state
1520
 * @to:  the target state or NULL for building a new one
1521
 * counter:  the counter for that transition
1522
 *
1523
 */
1524
static int
1525
xmlFAGenerateCountedEpsilonTransition(xmlRegParserCtxtPtr ctxt,
1526
0
      xmlRegStatePtr from, xmlRegStatePtr to, int counter) {
1527
0
    if (to == NULL) {
1528
0
  to = xmlRegStatePush(ctxt);
1529
0
        if (to == NULL)
1530
0
            return(-1);
1531
0
  ctxt->state = to;
1532
0
    }
1533
0
    xmlRegStateAddTrans(ctxt, from, NULL, to, counter, -1);
1534
0
    return(0);
1535
0
}
1536
1537
/**
1538
 * xmlFAGenerateCountedTransition:
1539
 * @ctxt:  a regexp parser context
1540
 * @from:  the from state
1541
 * @to:  the target state or NULL for building a new one
1542
 * counter:  the counter for that transition
1543
 *
1544
 */
1545
static int
1546
xmlFAGenerateCountedTransition(xmlRegParserCtxtPtr ctxt,
1547
0
      xmlRegStatePtr from, xmlRegStatePtr to, int counter) {
1548
0
    if (to == NULL) {
1549
0
  to = xmlRegStatePush(ctxt);
1550
0
        if (to == NULL)
1551
0
            return(-1);
1552
0
  ctxt->state = to;
1553
0
    }
1554
0
    xmlRegStateAddTrans(ctxt, from, NULL, to, -1, counter);
1555
0
    return(0);
1556
0
}
1557
1558
/**
1559
 * xmlFAGenerateTransitions:
1560
 * @ctxt:  a regexp parser context
1561
 * @from:  the from state
1562
 * @to:  the target state or NULL for building a new one
1563
 * @atom:  the atom generating the transition
1564
 *
1565
 * Returns 0 if success and -1 in case of error.
1566
 */
1567
static int
1568
xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from,
1569
0
                   xmlRegStatePtr to, xmlRegAtomPtr atom) {
1570
0
    xmlRegStatePtr end;
1571
0
    int nullable = 0;
1572
1573
0
    if (atom == NULL) {
1574
0
  ERROR("generate transition: atom == NULL");
1575
0
  return(-1);
1576
0
    }
1577
0
    if (atom->type == XML_REGEXP_SUBREG) {
1578
  /*
1579
   * this is a subexpression handling one should not need to
1580
   * create a new node except for XML_REGEXP_QUANT_RANGE.
1581
   */
1582
0
  if ((to != NULL) && (atom->stop != to) &&
1583
0
      (atom->quant != XML_REGEXP_QUANT_RANGE)) {
1584
      /*
1585
       * Generate an epsilon transition to link to the target
1586
       */
1587
0
      xmlFAGenerateEpsilonTransition(ctxt, atom->stop, to);
1588
#ifdef DV
1589
  } else if ((to == NULL) && (atom->quant != XML_REGEXP_QUANT_RANGE) &&
1590
       (atom->quant != XML_REGEXP_QUANT_ONCE)) {
1591
      to = xmlRegStatePush(ctxt, to);
1592
            if (to == NULL)
1593
                return(-1);
1594
      ctxt->state = to;
1595
      xmlFAGenerateEpsilonTransition(ctxt, atom->stop, to);
1596
#endif
1597
0
  }
1598
0
  switch (atom->quant) {
1599
0
      case XML_REGEXP_QUANT_OPT:
1600
0
    atom->quant = XML_REGEXP_QUANT_ONCE;
1601
    /*
1602
     * transition done to the state after end of atom.
1603
     *      1. set transition from atom start to new state
1604
     *      2. set transition from atom end to this state.
1605
     */
1606
0
                if (to == NULL) {
1607
0
                    xmlFAGenerateEpsilonTransition(ctxt, atom->start, 0);
1608
0
                    xmlFAGenerateEpsilonTransition(ctxt, atom->stop,
1609
0
                                                   ctxt->state);
1610
0
                } else {
1611
0
                    xmlFAGenerateEpsilonTransition(ctxt, atom->start, to);
1612
0
                }
1613
0
    break;
1614
0
      case XML_REGEXP_QUANT_MULT:
1615
0
    atom->quant = XML_REGEXP_QUANT_ONCE;
1616
0
    xmlFAGenerateEpsilonTransition(ctxt, atom->start, atom->stop);
1617
0
    xmlFAGenerateEpsilonTransition(ctxt, atom->stop, atom->start);
1618
0
    break;
1619
0
      case XML_REGEXP_QUANT_PLUS:
1620
0
    atom->quant = XML_REGEXP_QUANT_ONCE;
1621
0
    xmlFAGenerateEpsilonTransition(ctxt, atom->stop, atom->start);
1622
0
    break;
1623
0
      case XML_REGEXP_QUANT_RANGE: {
1624
0
    int counter;
1625
0
    xmlRegStatePtr inter, newstate;
1626
1627
    /*
1628
     * create the final state now if needed
1629
     */
1630
0
    if (to != NULL) {
1631
0
        newstate = to;
1632
0
    } else {
1633
0
        newstate = xmlRegStatePush(ctxt);
1634
0
                    if (newstate == NULL)
1635
0
                        return(-1);
1636
0
    }
1637
1638
    /*
1639
     * The principle here is to use counted transition
1640
     * to avoid explosion in the number of states in the
1641
     * graph. This is clearly more complex but should not
1642
     * be exploitable at runtime.
1643
     */
1644
0
    if ((atom->min == 0) && (atom->start0 == NULL)) {
1645
0
        xmlRegAtomPtr copy;
1646
        /*
1647
         * duplicate a transition based on atom to count next
1648
         * occurrences after 1. We cannot loop to atom->start
1649
         * directly because we need an epsilon transition to
1650
         * newstate.
1651
         */
1652
         /* ???? For some reason it seems we never reach that
1653
            case, I suppose this got optimized out before when
1654
      building the automata */
1655
0
        copy = xmlRegCopyAtom(ctxt, atom);
1656
0
        if (copy == NULL)
1657
0
            return(-1);
1658
0
        copy->quant = XML_REGEXP_QUANT_ONCE;
1659
0
        copy->min = 0;
1660
0
        copy->max = 0;
1661
1662
0
        if (xmlFAGenerateTransitions(ctxt, atom->start, NULL, copy)
1663
0
            < 0) {
1664
0
                        xmlRegFreeAtom(copy);
1665
0
      return(-1);
1666
0
                    }
1667
0
        inter = ctxt->state;
1668
0
        counter = xmlRegGetCounter(ctxt);
1669
0
                    if (counter < 0)
1670
0
                        return(-1);
1671
0
        ctxt->counters[counter].min = atom->min - 1;
1672
0
        ctxt->counters[counter].max = atom->max - 1;
1673
        /* count the number of times we see it again */
1674
0
        xmlFAGenerateCountedEpsilonTransition(ctxt, inter,
1675
0
               atom->stop, counter);
1676
        /* allow a way out based on the count */
1677
0
        xmlFAGenerateCountedTransition(ctxt, inter,
1678
0
                                 newstate, counter);
1679
        /* and also allow a direct exit for 0 */
1680
0
        xmlFAGenerateEpsilonTransition(ctxt, atom->start,
1681
0
                                       newstate);
1682
0
    } else {
1683
        /*
1684
         * either we need the atom at least once or there
1685
         * is an atom->start0 allowing to easily plug the
1686
         * epsilon transition.
1687
         */
1688
0
        counter = xmlRegGetCounter(ctxt);
1689
0
                    if (counter < 0)
1690
0
                        return(-1);
1691
0
        ctxt->counters[counter].min = atom->min - 1;
1692
0
        ctxt->counters[counter].max = atom->max - 1;
1693
        /* allow a way out based on the count */
1694
0
        xmlFAGenerateCountedTransition(ctxt, atom->stop,
1695
0
                                 newstate, counter);
1696
        /* count the number of times we see it again */
1697
0
        xmlFAGenerateCountedEpsilonTransition(ctxt, atom->stop,
1698
0
               atom->start, counter);
1699
        /* and if needed allow a direct exit for 0 */
1700
0
        if (atom->min == 0)
1701
0
      xmlFAGenerateEpsilonTransition(ctxt, atom->start0,
1702
0
                   newstate);
1703
1704
0
    }
1705
0
    atom->min = 0;
1706
0
    atom->max = 0;
1707
0
    atom->quant = XML_REGEXP_QUANT_ONCE;
1708
0
    ctxt->state = newstate;
1709
0
      }
1710
0
      default:
1711
0
    break;
1712
0
  }
1713
0
  if (xmlRegAtomPush(ctxt, atom) < 0)
1714
0
      return(-1);
1715
0
  return(0);
1716
0
    }
1717
0
    if ((atom->min == 0) && (atom->max == 0) &&
1718
0
               (atom->quant == XML_REGEXP_QUANT_RANGE)) {
1719
        /*
1720
   * we can discard the atom and generate an epsilon transition instead
1721
   */
1722
0
  if (to == NULL) {
1723
0
      to = xmlRegStatePush(ctxt);
1724
0
      if (to == NULL)
1725
0
    return(-1);
1726
0
  }
1727
0
  xmlFAGenerateEpsilonTransition(ctxt, from, to);
1728
0
  ctxt->state = to;
1729
0
  xmlRegFreeAtom(atom);
1730
0
  return(0);
1731
0
    }
1732
0
    if (to == NULL) {
1733
0
  to = xmlRegStatePush(ctxt);
1734
0
  if (to == NULL)
1735
0
      return(-1);
1736
0
    }
1737
0
    end = to;
1738
0
    if ((atom->quant == XML_REGEXP_QUANT_MULT) ||
1739
0
        (atom->quant == XML_REGEXP_QUANT_PLUS)) {
1740
  /*
1741
   * Do not pollute the target state by adding transitions from
1742
   * it as it is likely to be the shared target of multiple branches.
1743
   * So isolate with an epsilon transition.
1744
   */
1745
0
        xmlRegStatePtr tmp;
1746
1747
0
  tmp = xmlRegStatePush(ctxt);
1748
0
        if (tmp == NULL)
1749
0
      return(-1);
1750
0
  xmlFAGenerateEpsilonTransition(ctxt, tmp, to);
1751
0
  to = tmp;
1752
0
    }
1753
0
    if ((atom->quant == XML_REGEXP_QUANT_RANGE) &&
1754
0
        (atom->min == 0) && (atom->max > 0)) {
1755
0
  nullable = 1;
1756
0
  atom->min = 1;
1757
0
        if (atom->max == 1)
1758
0
      atom->quant = XML_REGEXP_QUANT_OPT;
1759
0
    }
1760
0
    xmlRegStateAddTrans(ctxt, from, atom, to, -1, -1);
1761
0
    ctxt->state = end;
1762
0
    switch (atom->quant) {
1763
0
  case XML_REGEXP_QUANT_OPT:
1764
0
      atom->quant = XML_REGEXP_QUANT_ONCE;
1765
0
      xmlFAGenerateEpsilonTransition(ctxt, from, to);
1766
0
      break;
1767
0
  case XML_REGEXP_QUANT_MULT:
1768
0
      atom->quant = XML_REGEXP_QUANT_ONCE;
1769
0
      xmlFAGenerateEpsilonTransition(ctxt, from, to);
1770
0
      xmlRegStateAddTrans(ctxt, to, atom, to, -1, -1);
1771
0
      break;
1772
0
  case XML_REGEXP_QUANT_PLUS:
1773
0
      atom->quant = XML_REGEXP_QUANT_ONCE;
1774
0
      xmlRegStateAddTrans(ctxt, to, atom, to, -1, -1);
1775
0
      break;
1776
0
  case XML_REGEXP_QUANT_RANGE:
1777
0
      if (nullable)
1778
0
    xmlFAGenerateEpsilonTransition(ctxt, from, to);
1779
0
      break;
1780
0
  default:
1781
0
      break;
1782
0
    }
1783
0
    if (xmlRegAtomPush(ctxt, atom) < 0)
1784
0
  return(-1);
1785
0
    return(0);
1786
0
}
1787
1788
/**
1789
 * xmlFAReduceEpsilonTransitions:
1790
 * @ctxt:  a regexp parser context
1791
 * @fromnr:  the from state
1792
 * @tonr:  the to state
1793
 * @counter:  should that transition be associated to a counted
1794
 *
1795
 */
1796
static void
1797
xmlFAReduceEpsilonTransitions(xmlRegParserCtxtPtr ctxt, int fromnr,
1798
0
                        int tonr, int counter) {
1799
0
    int transnr;
1800
0
    xmlRegStatePtr from;
1801
0
    xmlRegStatePtr to;
1802
1803
#ifdef DEBUG_REGEXP_GRAPH
1804
    printf("xmlFAReduceEpsilonTransitions(%d, %d)\n", fromnr, tonr);
1805
#endif
1806
0
    from = ctxt->states[fromnr];
1807
0
    if (from == NULL)
1808
0
  return;
1809
0
    to = ctxt->states[tonr];
1810
0
    if (to == NULL)
1811
0
  return;
1812
0
    if ((to->mark == XML_REGEXP_MARK_START) ||
1813
0
  (to->mark == XML_REGEXP_MARK_VISITED))
1814
0
  return;
1815
1816
0
    to->mark = XML_REGEXP_MARK_VISITED;
1817
0
    if (to->type == XML_REGEXP_FINAL_STATE) {
1818
#ifdef DEBUG_REGEXP_GRAPH
1819
  printf("State %d is final, so %d becomes final\n", tonr, fromnr);
1820
#endif
1821
0
  from->type = XML_REGEXP_FINAL_STATE;
1822
0
    }
1823
0
    for (transnr = 0;transnr < to->nbTrans;transnr++) {
1824
0
        xmlRegTransPtr t1 = &to->trans[transnr];
1825
0
        int tcounter;
1826
1827
0
        if (t1->to < 0)
1828
0
      continue;
1829
0
        if (t1->counter >= 0) {
1830
            /* assert(counter < 0); */
1831
0
            tcounter = t1->counter;
1832
0
        } else {
1833
0
            tcounter = counter;
1834
0
        }
1835
0
  if (t1->atom == NULL) {
1836
      /*
1837
       * Don't remove counted transitions
1838
       * Don't loop either
1839
       */
1840
0
      if (t1->to != fromnr) {
1841
0
    if (t1->count >= 0) {
1842
0
        xmlRegStateAddTrans(ctxt, from, NULL, ctxt->states[t1->to],
1843
0
          -1, t1->count);
1844
0
    } else {
1845
#ifdef DEBUG_REGEXP_GRAPH
1846
        printf("Found epsilon trans %d from %d to %d\n",
1847
         transnr, tonr, t1->to);
1848
#endif
1849
0
                    xmlFAReduceEpsilonTransitions(ctxt, fromnr, t1->to,
1850
0
                                                  tcounter);
1851
0
    }
1852
0
      }
1853
0
  } else {
1854
0
            xmlRegStateAddTrans(ctxt, from, t1->atom,
1855
0
                                ctxt->states[t1->to], tcounter, -1);
1856
0
  }
1857
0
    }
1858
0
}
1859
1860
/**
1861
 * xmlFAFinishReduceEpsilonTransitions:
1862
 * @ctxt:  a regexp parser context
1863
 * @fromnr:  the from state
1864
 * @tonr:  the to state
1865
 * @counter:  should that transition be associated to a counted
1866
 *
1867
 */
1868
static void
1869
0
xmlFAFinishReduceEpsilonTransitions(xmlRegParserCtxtPtr ctxt, int tonr) {
1870
0
    int transnr;
1871
0
    xmlRegStatePtr to;
1872
1873
0
    to = ctxt->states[tonr];
1874
0
    if (to == NULL)
1875
0
  return;
1876
0
    if ((to->mark == XML_REGEXP_MARK_START) ||
1877
0
  (to->mark == XML_REGEXP_MARK_NORMAL))
1878
0
  return;
1879
1880
0
    to->mark = XML_REGEXP_MARK_NORMAL;
1881
0
    for (transnr = 0;transnr < to->nbTrans;transnr++) {
1882
0
  xmlRegTransPtr t1 = &to->trans[transnr];
1883
0
  if ((t1->to >= 0) && (t1->atom == NULL))
1884
0
            xmlFAFinishReduceEpsilonTransitions(ctxt, t1->to);
1885
0
    }
1886
0
}
1887
1888
/**
1889
 * xmlFAEliminateSimpleEpsilonTransitions:
1890
 * @ctxt:  a regexp parser context
1891
 *
1892
 * Eliminating general epsilon transitions can get costly in the general
1893
 * algorithm due to the large amount of generated new transitions and
1894
 * associated comparisons. However for simple epsilon transition used just
1895
 * to separate building blocks when generating the automata this can be
1896
 * reduced to state elimination:
1897
 *    - if there exists an epsilon from X to Y
1898
 *    - if there is no other transition from X
1899
 * then X and Y are semantically equivalent and X can be eliminated
1900
 * If X is the start state then make Y the start state, else replace the
1901
 * target of all transitions to X by transitions to Y.
1902
 *
1903
 * If X is a final state, skip it.
1904
 * Otherwise it would be necessary to manipulate counters for this case when
1905
 * eliminating state 2:
1906
 * State 1 has a transition with an atom to state 2.
1907
 * State 2 is final and has an epsilon transition to state 1.
1908
 */
1909
static void
1910
0
xmlFAEliminateSimpleEpsilonTransitions(xmlRegParserCtxtPtr ctxt) {
1911
0
    int statenr, i, j, newto;
1912
0
    xmlRegStatePtr state, tmp;
1913
1914
0
    for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1915
0
  state = ctxt->states[statenr];
1916
0
  if (state == NULL)
1917
0
      continue;
1918
0
  if (state->nbTrans != 1)
1919
0
      continue;
1920
0
       if (state->type == XML_REGEXP_UNREACH_STATE ||
1921
0
           state->type == XML_REGEXP_FINAL_STATE)
1922
0
      continue;
1923
  /* is the only transition out a basic transition */
1924
0
  if ((state->trans[0].atom == NULL) &&
1925
0
      (state->trans[0].to >= 0) &&
1926
0
      (state->trans[0].to != statenr) &&
1927
0
      (state->trans[0].counter < 0) &&
1928
0
      (state->trans[0].count < 0)) {
1929
0
      newto = state->trans[0].to;
1930
1931
0
            if (state->type == XML_REGEXP_START_STATE) {
1932
#ifdef DEBUG_REGEXP_GRAPH
1933
    printf("Found simple epsilon trans from start %d to %d\n",
1934
           statenr, newto);
1935
#endif
1936
0
            } else {
1937
#ifdef DEBUG_REGEXP_GRAPH
1938
    printf("Found simple epsilon trans from %d to %d\n",
1939
           statenr, newto);
1940
#endif
1941
0
          for (i = 0;i < state->nbTransTo;i++) {
1942
0
        tmp = ctxt->states[state->transTo[i]];
1943
0
        for (j = 0;j < tmp->nbTrans;j++) {
1944
0
      if (tmp->trans[j].to == statenr) {
1945
#ifdef DEBUG_REGEXP_GRAPH
1946
          printf("Changed transition %d on %d to go to %d\n",
1947
           j, tmp->no, newto);
1948
#endif
1949
0
          tmp->trans[j].to = -1;
1950
0
          xmlRegStateAddTrans(ctxt, tmp, tmp->trans[j].atom,
1951
0
            ctxt->states[newto],
1952
0
                  tmp->trans[j].counter,
1953
0
            tmp->trans[j].count);
1954
0
      }
1955
0
        }
1956
0
    }
1957
0
    if (state->type == XML_REGEXP_FINAL_STATE)
1958
0
        ctxt->states[newto]->type = XML_REGEXP_FINAL_STATE;
1959
    /* eliminate the transition completely */
1960
0
    state->nbTrans = 0;
1961
1962
0
                state->type = XML_REGEXP_UNREACH_STATE;
1963
1964
0
      }
1965
1966
0
  }
1967
0
    }
1968
0
}
1969
/**
1970
 * xmlFAEliminateEpsilonTransitions:
1971
 * @ctxt:  a regexp parser context
1972
 *
1973
 */
1974
static void
1975
0
xmlFAEliminateEpsilonTransitions(xmlRegParserCtxtPtr ctxt) {
1976
0
    int statenr, transnr;
1977
0
    xmlRegStatePtr state;
1978
0
    int has_epsilon;
1979
1980
0
    if (ctxt->states == NULL) return;
1981
1982
    /*
1983
     * Eliminate simple epsilon transition and the associated unreachable
1984
     * states.
1985
     */
1986
0
    xmlFAEliminateSimpleEpsilonTransitions(ctxt);
1987
0
    for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
1988
0
  state = ctxt->states[statenr];
1989
0
  if ((state != NULL) && (state->type == XML_REGEXP_UNREACH_STATE)) {
1990
#ifdef DEBUG_REGEXP_GRAPH
1991
      printf("Removed unreachable state %d\n", statenr);
1992
#endif
1993
0
      xmlRegFreeState(state);
1994
0
      ctxt->states[statenr] = NULL;
1995
0
  }
1996
0
    }
1997
1998
0
    has_epsilon = 0;
1999
2000
    /*
2001
     * Build the completed transitions bypassing the epsilons
2002
     * Use a marking algorithm to avoid loops
2003
     * Mark sink states too.
2004
     * Process from the latest states backward to the start when
2005
     * there is long cascading epsilon chains this minimize the
2006
     * recursions and transition compares when adding the new ones
2007
     */
2008
0
    for (statenr = ctxt->nbStates - 1;statenr >= 0;statenr--) {
2009
0
  state = ctxt->states[statenr];
2010
0
  if (state == NULL)
2011
0
      continue;
2012
0
  if ((state->nbTrans == 0) &&
2013
0
      (state->type != XML_REGEXP_FINAL_STATE)) {
2014
0
      state->type = XML_REGEXP_SINK_STATE;
2015
0
  }
2016
0
  for (transnr = 0;transnr < state->nbTrans;transnr++) {
2017
0
      if ((state->trans[transnr].atom == NULL) &&
2018
0
    (state->trans[transnr].to >= 0)) {
2019
0
    if (state->trans[transnr].to == statenr) {
2020
0
        state->trans[transnr].to = -1;
2021
#ifdef DEBUG_REGEXP_GRAPH
2022
        printf("Removed loopback epsilon trans %d on %d\n",
2023
         transnr, statenr);
2024
#endif
2025
0
    } else if (state->trans[transnr].count < 0) {
2026
0
        int newto = state->trans[transnr].to;
2027
2028
#ifdef DEBUG_REGEXP_GRAPH
2029
        printf("Found epsilon trans %d from %d to %d\n",
2030
         transnr, statenr, newto);
2031
#endif
2032
0
        has_epsilon = 1;
2033
0
        state->trans[transnr].to = -2;
2034
0
        state->mark = XML_REGEXP_MARK_START;
2035
0
        xmlFAReduceEpsilonTransitions(ctxt, statenr,
2036
0
              newto, state->trans[transnr].counter);
2037
0
        xmlFAFinishReduceEpsilonTransitions(ctxt, newto);
2038
0
        state->mark = XML_REGEXP_MARK_NORMAL;
2039
#ifdef DEBUG_REGEXP_GRAPH
2040
    } else {
2041
        printf("Found counted transition %d on %d\n",
2042
         transnr, statenr);
2043
#endif
2044
0
          }
2045
0
      }
2046
0
  }
2047
0
    }
2048
    /*
2049
     * Eliminate the epsilon transitions
2050
     */
2051
0
    if (has_epsilon) {
2052
0
  for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2053
0
      state = ctxt->states[statenr];
2054
0
      if (state == NULL)
2055
0
    continue;
2056
0
      for (transnr = 0;transnr < state->nbTrans;transnr++) {
2057
0
    xmlRegTransPtr trans = &(state->trans[transnr]);
2058
0
    if ((trans->atom == NULL) &&
2059
0
        (trans->count < 0) &&
2060
0
        (trans->to >= 0)) {
2061
0
        trans->to = -1;
2062
0
    }
2063
0
      }
2064
0
  }
2065
0
    }
2066
2067
    /*
2068
     * Use this pass to detect unreachable states too
2069
     */
2070
0
    for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2071
0
  state = ctxt->states[statenr];
2072
0
  if (state != NULL)
2073
0
      state->reached = XML_REGEXP_MARK_NORMAL;
2074
0
    }
2075
0
    state = ctxt->states[0];
2076
0
    if (state != NULL)
2077
0
  state->reached = XML_REGEXP_MARK_START;
2078
0
    while (state != NULL) {
2079
0
  xmlRegStatePtr target = NULL;
2080
0
  state->reached = XML_REGEXP_MARK_VISITED;
2081
  /*
2082
   * Mark all states reachable from the current reachable state
2083
   */
2084
0
  for (transnr = 0;transnr < state->nbTrans;transnr++) {
2085
0
      if ((state->trans[transnr].to >= 0) &&
2086
0
    ((state->trans[transnr].atom != NULL) ||
2087
0
     (state->trans[transnr].count >= 0))) {
2088
0
    int newto = state->trans[transnr].to;
2089
2090
0
    if (ctxt->states[newto] == NULL)
2091
0
        continue;
2092
0
    if (ctxt->states[newto]->reached == XML_REGEXP_MARK_NORMAL) {
2093
0
        ctxt->states[newto]->reached = XML_REGEXP_MARK_START;
2094
0
        target = ctxt->states[newto];
2095
0
    }
2096
0
      }
2097
0
  }
2098
2099
  /*
2100
   * find the next accessible state not explored
2101
   */
2102
0
  if (target == NULL) {
2103
0
      for (statenr = 1;statenr < ctxt->nbStates;statenr++) {
2104
0
    state = ctxt->states[statenr];
2105
0
    if ((state != NULL) && (state->reached ==
2106
0
      XML_REGEXP_MARK_START)) {
2107
0
        target = state;
2108
0
        break;
2109
0
    }
2110
0
      }
2111
0
  }
2112
0
  state = target;
2113
0
    }
2114
0
    for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2115
0
  state = ctxt->states[statenr];
2116
0
  if ((state != NULL) && (state->reached == XML_REGEXP_MARK_NORMAL)) {
2117
#ifdef DEBUG_REGEXP_GRAPH
2118
      printf("Removed unreachable state %d\n", statenr);
2119
#endif
2120
0
      xmlRegFreeState(state);
2121
0
      ctxt->states[statenr] = NULL;
2122
0
  }
2123
0
    }
2124
2125
0
}
2126
2127
static int
2128
0
xmlFACompareRanges(xmlRegRangePtr range1, xmlRegRangePtr range2) {
2129
0
    int ret = 0;
2130
2131
0
    if ((range1->type == XML_REGEXP_RANGES) ||
2132
0
        (range2->type == XML_REGEXP_RANGES) ||
2133
0
        (range2->type == XML_REGEXP_SUBREG) ||
2134
0
        (range1->type == XML_REGEXP_SUBREG) ||
2135
0
        (range1->type == XML_REGEXP_STRING) ||
2136
0
        (range2->type == XML_REGEXP_STRING))
2137
0
  return(-1);
2138
2139
    /* put them in order */
2140
0
    if (range1->type > range2->type) {
2141
0
        xmlRegRangePtr tmp;
2142
2143
0
  tmp = range1;
2144
0
  range1 = range2;
2145
0
  range2 = tmp;
2146
0
    }
2147
0
    if ((range1->type == XML_REGEXP_ANYCHAR) ||
2148
0
        (range2->type == XML_REGEXP_ANYCHAR)) {
2149
0
  ret = 1;
2150
0
    } else if ((range1->type == XML_REGEXP_EPSILON) ||
2151
0
               (range2->type == XML_REGEXP_EPSILON)) {
2152
0
  return(0);
2153
0
    } else if (range1->type == range2->type) {
2154
0
        if (range1->type != XML_REGEXP_CHARVAL)
2155
0
            ret = 1;
2156
0
        else if ((range1->end < range2->start) ||
2157
0
           (range2->end < range1->start))
2158
0
      ret = 0;
2159
0
  else
2160
0
      ret = 1;
2161
0
    } else if (range1->type == XML_REGEXP_CHARVAL) {
2162
0
        int codepoint;
2163
0
  int neg = 0;
2164
2165
  /*
2166
   * just check all codepoints in the range for acceptance,
2167
   * this is usually way cheaper since done only once at
2168
   * compilation than testing over and over at runtime or
2169
   * pushing too many states when evaluating.
2170
   */
2171
0
  if (((range1->neg == 0) && (range2->neg != 0)) ||
2172
0
      ((range1->neg != 0) && (range2->neg == 0)))
2173
0
      neg = 1;
2174
2175
0
  for (codepoint = range1->start;codepoint <= range1->end ;codepoint++) {
2176
0
      ret = xmlRegCheckCharacterRange(range2->type, codepoint,
2177
0
              0, range2->start, range2->end,
2178
0
              range2->blockName);
2179
0
      if (ret < 0)
2180
0
          return(-1);
2181
0
      if (((neg == 1) && (ret == 0)) ||
2182
0
          ((neg == 0) && (ret == 1)))
2183
0
    return(1);
2184
0
  }
2185
0
  return(0);
2186
0
    } else if ((range1->type == XML_REGEXP_BLOCK_NAME) ||
2187
0
               (range2->type == XML_REGEXP_BLOCK_NAME)) {
2188
0
  if (range1->type == range2->type) {
2189
0
      ret = xmlStrEqual(range1->blockName, range2->blockName);
2190
0
  } else {
2191
      /*
2192
       * comparing a block range with anything else is way
2193
       * too costly, and maintaining the table is like too much
2194
       * memory too, so let's force the automata to save state
2195
       * here.
2196
       */
2197
0
      return(1);
2198
0
  }
2199
0
    } else if ((range1->type < XML_REGEXP_LETTER) ||
2200
0
               (range2->type < XML_REGEXP_LETTER)) {
2201
0
  if ((range1->type == XML_REGEXP_ANYSPACE) &&
2202
0
      (range2->type == XML_REGEXP_NOTSPACE))
2203
0
      ret = 0;
2204
0
  else if ((range1->type == XML_REGEXP_INITNAME) &&
2205
0
           (range2->type == XML_REGEXP_NOTINITNAME))
2206
0
      ret = 0;
2207
0
  else if ((range1->type == XML_REGEXP_NAMECHAR) &&
2208
0
           (range2->type == XML_REGEXP_NOTNAMECHAR))
2209
0
      ret = 0;
2210
0
  else if ((range1->type == XML_REGEXP_DECIMAL) &&
2211
0
           (range2->type == XML_REGEXP_NOTDECIMAL))
2212
0
      ret = 0;
2213
0
  else if ((range1->type == XML_REGEXP_REALCHAR) &&
2214
0
           (range2->type == XML_REGEXP_NOTREALCHAR))
2215
0
      ret = 0;
2216
0
  else {
2217
      /* same thing to limit complexity */
2218
0
      return(1);
2219
0
  }
2220
0
    } else {
2221
0
        ret = 0;
2222
        /* range1->type < range2->type here */
2223
0
        switch (range1->type) {
2224
0
      case XML_REGEXP_LETTER:
2225
           /* all disjoint except in the subgroups */
2226
0
           if ((range2->type == XML_REGEXP_LETTER_UPPERCASE) ||
2227
0
         (range2->type == XML_REGEXP_LETTER_LOWERCASE) ||
2228
0
         (range2->type == XML_REGEXP_LETTER_TITLECASE) ||
2229
0
         (range2->type == XML_REGEXP_LETTER_MODIFIER) ||
2230
0
         (range2->type == XML_REGEXP_LETTER_OTHERS))
2231
0
         ret = 1;
2232
0
     break;
2233
0
      case XML_REGEXP_MARK:
2234
0
           if ((range2->type == XML_REGEXP_MARK_NONSPACING) ||
2235
0
         (range2->type == XML_REGEXP_MARK_SPACECOMBINING) ||
2236
0
         (range2->type == XML_REGEXP_MARK_ENCLOSING))
2237
0
         ret = 1;
2238
0
     break;
2239
0
      case XML_REGEXP_NUMBER:
2240
0
           if ((range2->type == XML_REGEXP_NUMBER_DECIMAL) ||
2241
0
         (range2->type == XML_REGEXP_NUMBER_LETTER) ||
2242
0
         (range2->type == XML_REGEXP_NUMBER_OTHERS))
2243
0
         ret = 1;
2244
0
     break;
2245
0
      case XML_REGEXP_PUNCT:
2246
0
           if ((range2->type == XML_REGEXP_PUNCT_CONNECTOR) ||
2247
0
         (range2->type == XML_REGEXP_PUNCT_DASH) ||
2248
0
         (range2->type == XML_REGEXP_PUNCT_OPEN) ||
2249
0
         (range2->type == XML_REGEXP_PUNCT_CLOSE) ||
2250
0
         (range2->type == XML_REGEXP_PUNCT_INITQUOTE) ||
2251
0
         (range2->type == XML_REGEXP_PUNCT_FINQUOTE) ||
2252
0
         (range2->type == XML_REGEXP_PUNCT_OTHERS))
2253
0
         ret = 1;
2254
0
     break;
2255
0
      case XML_REGEXP_SEPAR:
2256
0
           if ((range2->type == XML_REGEXP_SEPAR_SPACE) ||
2257
0
         (range2->type == XML_REGEXP_SEPAR_LINE) ||
2258
0
         (range2->type == XML_REGEXP_SEPAR_PARA))
2259
0
         ret = 1;
2260
0
     break;
2261
0
      case XML_REGEXP_SYMBOL:
2262
0
           if ((range2->type == XML_REGEXP_SYMBOL_MATH) ||
2263
0
         (range2->type == XML_REGEXP_SYMBOL_CURRENCY) ||
2264
0
         (range2->type == XML_REGEXP_SYMBOL_MODIFIER) ||
2265
0
         (range2->type == XML_REGEXP_SYMBOL_OTHERS))
2266
0
         ret = 1;
2267
0
     break;
2268
0
      case XML_REGEXP_OTHER:
2269
0
           if ((range2->type == XML_REGEXP_OTHER_CONTROL) ||
2270
0
         (range2->type == XML_REGEXP_OTHER_FORMAT) ||
2271
0
         (range2->type == XML_REGEXP_OTHER_PRIVATE))
2272
0
         ret = 1;
2273
0
     break;
2274
0
            default:
2275
0
           if ((range2->type >= XML_REGEXP_LETTER) &&
2276
0
         (range2->type < XML_REGEXP_BLOCK_NAME))
2277
0
         ret = 0;
2278
0
     else {
2279
         /* safety net ! */
2280
0
         return(1);
2281
0
     }
2282
0
  }
2283
0
    }
2284
0
    if (((range1->neg == 0) && (range2->neg != 0)) ||
2285
0
        ((range1->neg != 0) && (range2->neg == 0)))
2286
0
  ret = !ret;
2287
0
    return(ret);
2288
0
}
2289
2290
/**
2291
 * xmlFACompareAtomTypes:
2292
 * @type1:  an atom type
2293
 * @type2:  an atom type
2294
 *
2295
 * Compares two atoms type to check whether they intersect in some ways,
2296
 * this is used by xmlFACompareAtoms only
2297
 *
2298
 * Returns 1 if they may intersect and 0 otherwise
2299
 */
2300
static int
2301
0
xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
2302
0
    if ((type1 == XML_REGEXP_EPSILON) ||
2303
0
        (type1 == XML_REGEXP_CHARVAL) ||
2304
0
  (type1 == XML_REGEXP_RANGES) ||
2305
0
  (type1 == XML_REGEXP_SUBREG) ||
2306
0
  (type1 == XML_REGEXP_STRING) ||
2307
0
  (type1 == XML_REGEXP_ANYCHAR))
2308
0
  return(1);
2309
0
    if ((type2 == XML_REGEXP_EPSILON) ||
2310
0
        (type2 == XML_REGEXP_CHARVAL) ||
2311
0
  (type2 == XML_REGEXP_RANGES) ||
2312
0
  (type2 == XML_REGEXP_SUBREG) ||
2313
0
  (type2 == XML_REGEXP_STRING) ||
2314
0
  (type2 == XML_REGEXP_ANYCHAR))
2315
0
  return(1);
2316
2317
0
    if (type1 == type2) return(1);
2318
2319
    /* simplify subsequent compares by making sure type1 < type2 */
2320
0
    if (type1 > type2) {
2321
0
        xmlRegAtomType tmp = type1;
2322
0
  type1 = type2;
2323
0
  type2 = tmp;
2324
0
    }
2325
0
    switch (type1) {
2326
0
        case XML_REGEXP_ANYSPACE: /* \s */
2327
      /* can't be a letter, number, mark, punctuation, symbol */
2328
0
      if ((type2 == XML_REGEXP_NOTSPACE) ||
2329
0
    ((type2 >= XML_REGEXP_LETTER) &&
2330
0
     (type2 <= XML_REGEXP_LETTER_OTHERS)) ||
2331
0
          ((type2 >= XML_REGEXP_NUMBER) &&
2332
0
     (type2 <= XML_REGEXP_NUMBER_OTHERS)) ||
2333
0
          ((type2 >= XML_REGEXP_MARK) &&
2334
0
     (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2335
0
          ((type2 >= XML_REGEXP_PUNCT) &&
2336
0
     (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2337
0
          ((type2 >= XML_REGEXP_SYMBOL) &&
2338
0
     (type2 <= XML_REGEXP_SYMBOL_OTHERS))
2339
0
          ) return(0);
2340
0
      break;
2341
0
        case XML_REGEXP_NOTSPACE: /* \S */
2342
0
      break;
2343
0
        case XML_REGEXP_INITNAME: /* \l */
2344
      /* can't be a number, mark, separator, punctuation, symbol or other */
2345
0
      if ((type2 == XML_REGEXP_NOTINITNAME) ||
2346
0
          ((type2 >= XML_REGEXP_NUMBER) &&
2347
0
     (type2 <= XML_REGEXP_NUMBER_OTHERS)) ||
2348
0
          ((type2 >= XML_REGEXP_MARK) &&
2349
0
     (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2350
0
          ((type2 >= XML_REGEXP_SEPAR) &&
2351
0
     (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2352
0
          ((type2 >= XML_REGEXP_PUNCT) &&
2353
0
     (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2354
0
          ((type2 >= XML_REGEXP_SYMBOL) &&
2355
0
     (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2356
0
          ((type2 >= XML_REGEXP_OTHER) &&
2357
0
     (type2 <= XML_REGEXP_OTHER_NA))
2358
0
    ) return(0);
2359
0
      break;
2360
0
        case XML_REGEXP_NOTINITNAME: /* \L */
2361
0
      break;
2362
0
        case XML_REGEXP_NAMECHAR: /* \c */
2363
      /* can't be a mark, separator, punctuation, symbol or other */
2364
0
      if ((type2 == XML_REGEXP_NOTNAMECHAR) ||
2365
0
          ((type2 >= XML_REGEXP_MARK) &&
2366
0
     (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2367
0
          ((type2 >= XML_REGEXP_PUNCT) &&
2368
0
     (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2369
0
          ((type2 >= XML_REGEXP_SEPAR) &&
2370
0
     (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2371
0
          ((type2 >= XML_REGEXP_SYMBOL) &&
2372
0
     (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2373
0
          ((type2 >= XML_REGEXP_OTHER) &&
2374
0
     (type2 <= XML_REGEXP_OTHER_NA))
2375
0
    ) return(0);
2376
0
      break;
2377
0
        case XML_REGEXP_NOTNAMECHAR: /* \C */
2378
0
      break;
2379
0
        case XML_REGEXP_DECIMAL: /* \d */
2380
      /* can't be a letter, mark, separator, punctuation, symbol or other */
2381
0
      if ((type2 == XML_REGEXP_NOTDECIMAL) ||
2382
0
          (type2 == XML_REGEXP_REALCHAR) ||
2383
0
    ((type2 >= XML_REGEXP_LETTER) &&
2384
0
     (type2 <= XML_REGEXP_LETTER_OTHERS)) ||
2385
0
          ((type2 >= XML_REGEXP_MARK) &&
2386
0
     (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2387
0
          ((type2 >= XML_REGEXP_PUNCT) &&
2388
0
     (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2389
0
          ((type2 >= XML_REGEXP_SEPAR) &&
2390
0
     (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2391
0
          ((type2 >= XML_REGEXP_SYMBOL) &&
2392
0
     (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2393
0
          ((type2 >= XML_REGEXP_OTHER) &&
2394
0
     (type2 <= XML_REGEXP_OTHER_NA))
2395
0
    )return(0);
2396
0
      break;
2397
0
        case XML_REGEXP_NOTDECIMAL: /* \D */
2398
0
      break;
2399
0
        case XML_REGEXP_REALCHAR: /* \w */
2400
      /* can't be a mark, separator, punctuation, symbol or other */
2401
0
      if ((type2 == XML_REGEXP_NOTDECIMAL) ||
2402
0
          ((type2 >= XML_REGEXP_MARK) &&
2403
0
     (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
2404
0
          ((type2 >= XML_REGEXP_PUNCT) &&
2405
0
     (type2 <= XML_REGEXP_PUNCT_OTHERS)) ||
2406
0
          ((type2 >= XML_REGEXP_SEPAR) &&
2407
0
     (type2 <= XML_REGEXP_SEPAR_PARA)) ||
2408
0
          ((type2 >= XML_REGEXP_SYMBOL) &&
2409
0
     (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ||
2410
0
          ((type2 >= XML_REGEXP_OTHER) &&
2411
0
     (type2 <= XML_REGEXP_OTHER_NA))
2412
0
    )return(0);
2413
0
      break;
2414
0
        case XML_REGEXP_NOTREALCHAR: /* \W */
2415
0
      break;
2416
  /*
2417
   * at that point we know both type 1 and type2 are from
2418
   * character categories are ordered and are different,
2419
   * it becomes simple because this is a partition
2420
   */
2421
0
        case XML_REGEXP_LETTER:
2422
0
      if (type2 <= XML_REGEXP_LETTER_OTHERS)
2423
0
          return(1);
2424
0
      return(0);
2425
0
        case XML_REGEXP_LETTER_UPPERCASE:
2426
0
        case XML_REGEXP_LETTER_LOWERCASE:
2427
0
        case XML_REGEXP_LETTER_TITLECASE:
2428
0
        case XML_REGEXP_LETTER_MODIFIER:
2429
0
        case XML_REGEXP_LETTER_OTHERS:
2430
0
      return(0);
2431
0
        case XML_REGEXP_MARK:
2432
0
      if (type2 <= XML_REGEXP_MARK_ENCLOSING)
2433
0
          return(1);
2434
0
      return(0);
2435
0
        case XML_REGEXP_MARK_NONSPACING:
2436
0
        case XML_REGEXP_MARK_SPACECOMBINING:
2437
0
        case XML_REGEXP_MARK_ENCLOSING:
2438
0
      return(0);
2439
0
        case XML_REGEXP_NUMBER:
2440
0
      if (type2 <= XML_REGEXP_NUMBER_OTHERS)
2441
0
          return(1);
2442
0
      return(0);
2443
0
        case XML_REGEXP_NUMBER_DECIMAL:
2444
0
        case XML_REGEXP_NUMBER_LETTER:
2445
0
        case XML_REGEXP_NUMBER_OTHERS:
2446
0
      return(0);
2447
0
        case XML_REGEXP_PUNCT:
2448
0
      if (type2 <= XML_REGEXP_PUNCT_OTHERS)
2449
0
          return(1);
2450
0
      return(0);
2451
0
        case XML_REGEXP_PUNCT_CONNECTOR:
2452
0
        case XML_REGEXP_PUNCT_DASH:
2453
0
        case XML_REGEXP_PUNCT_OPEN:
2454
0
        case XML_REGEXP_PUNCT_CLOSE:
2455
0
        case XML_REGEXP_PUNCT_INITQUOTE:
2456
0
        case XML_REGEXP_PUNCT_FINQUOTE:
2457
0
        case XML_REGEXP_PUNCT_OTHERS:
2458
0
      return(0);
2459
0
        case XML_REGEXP_SEPAR:
2460
0
      if (type2 <= XML_REGEXP_SEPAR_PARA)
2461
0
          return(1);
2462
0
      return(0);
2463
0
        case XML_REGEXP_SEPAR_SPACE:
2464
0
        case XML_REGEXP_SEPAR_LINE:
2465
0
        case XML_REGEXP_SEPAR_PARA:
2466
0
      return(0);
2467
0
        case XML_REGEXP_SYMBOL:
2468
0
      if (type2 <= XML_REGEXP_SYMBOL_OTHERS)
2469
0
          return(1);
2470
0
      return(0);
2471
0
        case XML_REGEXP_SYMBOL_MATH:
2472
0
        case XML_REGEXP_SYMBOL_CURRENCY:
2473
0
        case XML_REGEXP_SYMBOL_MODIFIER:
2474
0
        case XML_REGEXP_SYMBOL_OTHERS:
2475
0
      return(0);
2476
0
        case XML_REGEXP_OTHER:
2477
0
      if (type2 <= XML_REGEXP_OTHER_NA)
2478
0
          return(1);
2479
0
      return(0);
2480
0
        case XML_REGEXP_OTHER_CONTROL:
2481
0
        case XML_REGEXP_OTHER_FORMAT:
2482
0
        case XML_REGEXP_OTHER_PRIVATE:
2483
0
        case XML_REGEXP_OTHER_NA:
2484
0
      return(0);
2485
0
  default:
2486
0
      break;
2487
0
    }
2488
0
    return(1);
2489
0
}
2490
2491
/**
2492
 * xmlFAEqualAtoms:
2493
 * @atom1:  an atom
2494
 * @atom2:  an atom
2495
 * @deep: if not set only compare string pointers
2496
 *
2497
 * Compares two atoms to check whether they are the same exactly
2498
 * this is used to remove equivalent transitions
2499
 *
2500
 * Returns 1 if same and 0 otherwise
2501
 */
2502
static int
2503
0
xmlFAEqualAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2, int deep) {
2504
0
    int ret = 0;
2505
2506
0
    if (atom1 == atom2)
2507
0
  return(1);
2508
0
    if ((atom1 == NULL) || (atom2 == NULL))
2509
0
  return(0);
2510
2511
0
    if (atom1->type != atom2->type)
2512
0
        return(0);
2513
0
    switch (atom1->type) {
2514
0
        case XML_REGEXP_EPSILON:
2515
0
      ret = 0;
2516
0
      break;
2517
0
        case XML_REGEXP_STRING:
2518
0
            if (!deep)
2519
0
                ret = (atom1->valuep == atom2->valuep);
2520
0
            else
2521
0
                ret = xmlStrEqual((xmlChar *)atom1->valuep,
2522
0
                                  (xmlChar *)atom2->valuep);
2523
0
      break;
2524
0
        case XML_REGEXP_CHARVAL:
2525
0
      ret = (atom1->codepoint == atom2->codepoint);
2526
0
      break;
2527
0
  case XML_REGEXP_RANGES:
2528
      /* too hard to do in the general case */
2529
0
      ret = 0;
2530
0
  default:
2531
0
      break;
2532
0
    }
2533
0
    return(ret);
2534
0
}
2535
2536
/**
2537
 * xmlFACompareAtoms:
2538
 * @atom1:  an atom
2539
 * @atom2:  an atom
2540
 * @deep: if not set only compare string pointers
2541
 *
2542
 * Compares two atoms to check whether they intersect in some ways,
2543
 * this is used by xmlFAComputesDeterminism and xmlFARecurseDeterminism only
2544
 *
2545
 * Returns 1 if yes and 0 otherwise
2546
 */
2547
static int
2548
0
xmlFACompareAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2, int deep) {
2549
0
    int ret = 1;
2550
2551
0
    if (atom1 == atom2)
2552
0
  return(1);
2553
0
    if ((atom1 == NULL) || (atom2 == NULL))
2554
0
  return(0);
2555
2556
0
    if ((atom1->type == XML_REGEXP_ANYCHAR) ||
2557
0
        (atom2->type == XML_REGEXP_ANYCHAR))
2558
0
  return(1);
2559
2560
0
    if (atom1->type > atom2->type) {
2561
0
  xmlRegAtomPtr tmp;
2562
0
  tmp = atom1;
2563
0
  atom1 = atom2;
2564
0
  atom2 = tmp;
2565
0
    }
2566
0
    if (atom1->type != atom2->type) {
2567
0
        ret = xmlFACompareAtomTypes(atom1->type, atom2->type);
2568
  /* if they can't intersect at the type level break now */
2569
0
  if (ret == 0)
2570
0
      return(0);
2571
0
    }
2572
0
    switch (atom1->type) {
2573
0
        case XML_REGEXP_STRING:
2574
0
            if (!deep)
2575
0
                ret = (atom1->valuep != atom2->valuep);
2576
0
            else {
2577
0
                xmlChar *val1 = (xmlChar *)atom1->valuep;
2578
0
                xmlChar *val2 = (xmlChar *)atom2->valuep;
2579
0
                int compound1 = (xmlStrchr(val1, '|') != NULL);
2580
0
                int compound2 = (xmlStrchr(val2, '|') != NULL);
2581
2582
                /* Ignore negative match flag for ##other namespaces */
2583
0
                if (compound1 != compound2)
2584
0
                    return(0);
2585
2586
0
                ret = xmlRegStrEqualWildcard(val1, val2);
2587
0
            }
2588
0
      break;
2589
0
        case XML_REGEXP_EPSILON:
2590
0
      goto not_determinist;
2591
0
        case XML_REGEXP_CHARVAL:
2592
0
      if (atom2->type == XML_REGEXP_CHARVAL) {
2593
0
    ret = (atom1->codepoint == atom2->codepoint);
2594
0
      } else {
2595
0
          ret = xmlRegCheckCharacter(atom2, atom1->codepoint);
2596
0
    if (ret < 0)
2597
0
        ret = 1;
2598
0
      }
2599
0
      break;
2600
0
        case XML_REGEXP_RANGES:
2601
0
      if (atom2->type == XML_REGEXP_RANGES) {
2602
0
          int i, j, res;
2603
0
    xmlRegRangePtr r1, r2;
2604
2605
    /*
2606
     * need to check that none of the ranges eventually matches
2607
     */
2608
0
    for (i = 0;i < atom1->nbRanges;i++) {
2609
0
        for (j = 0;j < atom2->nbRanges;j++) {
2610
0
      r1 = atom1->ranges[i];
2611
0
      r2 = atom2->ranges[j];
2612
0
      res = xmlFACompareRanges(r1, r2);
2613
0
      if (res == 1) {
2614
0
          ret = 1;
2615
0
          goto done;
2616
0
      }
2617
0
        }
2618
0
    }
2619
0
    ret = 0;
2620
0
      }
2621
0
      break;
2622
0
  default:
2623
0
      goto not_determinist;
2624
0
    }
2625
0
done:
2626
0
    if (atom1->neg != atom2->neg) {
2627
0
        ret = !ret;
2628
0
    }
2629
0
    if (ret == 0)
2630
0
        return(0);
2631
0
not_determinist:
2632
0
    return(1);
2633
0
}
2634
2635
/**
2636
 * xmlFARecurseDeterminism:
2637
 * @ctxt:  a regexp parser context
2638
 *
2639
 * Check whether the associated regexp is determinist,
2640
 * should be called after xmlFAEliminateEpsilonTransitions()
2641
 *
2642
 */
2643
static int
2644
xmlFARecurseDeterminism(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state,
2645
0
                  int fromnr, int tonr, xmlRegAtomPtr atom) {
2646
0
    int ret = 1;
2647
0
    int res;
2648
0
    int transnr, nbTrans;
2649
0
    xmlRegTransPtr t1;
2650
0
    int deep = 1;
2651
2652
0
    if (state == NULL)
2653
0
  return(ret);
2654
0
    if (state->markd == XML_REGEXP_MARK_VISITED)
2655
0
  return(ret);
2656
2657
0
    if (ctxt->flags & AM_AUTOMATA_RNG)
2658
0
        deep = 0;
2659
2660
    /*
2661
     * don't recurse on transitions potentially added in the course of
2662
     * the elimination.
2663
     */
2664
0
    nbTrans = state->nbTrans;
2665
0
    for (transnr = 0;transnr < nbTrans;transnr++) {
2666
0
  t1 = &(state->trans[transnr]);
2667
  /*
2668
   * check transitions conflicting with the one looked at
2669
   */
2670
0
        if ((t1->to < 0) || (t1->to == fromnr))
2671
0
            continue;
2672
0
  if (t1->atom == NULL) {
2673
0
      state->markd = XML_REGEXP_MARK_VISITED;
2674
0
      res = xmlFARecurseDeterminism(ctxt, ctxt->states[t1->to],
2675
0
                              fromnr, tonr, atom);
2676
0
      if (res == 0) {
2677
0
          ret = 0;
2678
    /* t1->nd = 1; */
2679
0
      }
2680
0
      continue;
2681
0
  }
2682
0
  if (xmlFACompareAtoms(t1->atom, atom, deep)) {
2683
            /* Treat equal transitions as deterministic. */
2684
0
            if ((t1->to != tonr) ||
2685
0
                (!xmlFAEqualAtoms(t1->atom, atom, deep)))
2686
0
                ret = 0;
2687
      /* mark the transition as non-deterministic */
2688
0
      t1->nd = 1;
2689
0
  }
2690
0
    }
2691
0
    return(ret);
2692
0
}
2693
2694
/**
2695
 * xmlFAFinishRecurseDeterminism:
2696
 * @ctxt:  a regexp parser context
2697
 *
2698
 * Reset flags after checking determinism.
2699
 */
2700
static void
2701
0
xmlFAFinishRecurseDeterminism(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state) {
2702
0
    int transnr, nbTrans;
2703
2704
0
    if (state == NULL)
2705
0
  return;
2706
0
    if (state->markd != XML_REGEXP_MARK_VISITED)
2707
0
  return;
2708
0
    state->markd = 0;
2709
2710
0
    nbTrans = state->nbTrans;
2711
0
    for (transnr = 0; transnr < nbTrans; transnr++) {
2712
0
  xmlRegTransPtr t1 = &state->trans[transnr];
2713
0
  if ((t1->atom == NULL) && (t1->to >= 0))
2714
0
      xmlFAFinishRecurseDeterminism(ctxt, ctxt->states[t1->to]);
2715
0
    }
2716
0
}
2717
2718
/**
2719
 * xmlFAComputesDeterminism:
2720
 * @ctxt:  a regexp parser context
2721
 *
2722
 * Check whether the associated regexp is determinist,
2723
 * should be called after xmlFAEliminateEpsilonTransitions()
2724
 *
2725
 */
2726
static int
2727
0
xmlFAComputesDeterminism(xmlRegParserCtxtPtr ctxt) {
2728
0
    int statenr, transnr;
2729
0
    xmlRegStatePtr state;
2730
0
    xmlRegTransPtr t1, t2, last;
2731
0
    int i;
2732
0
    int ret = 1;
2733
0
    int deep = 1;
2734
2735
#ifdef DEBUG_REGEXP_GRAPH
2736
    printf("xmlFAComputesDeterminism\n");
2737
    xmlRegPrintCtxt(stdout, ctxt);
2738
#endif
2739
0
    if (ctxt->determinist != -1)
2740
0
  return(ctxt->determinist);
2741
2742
0
    if (ctxt->flags & AM_AUTOMATA_RNG)
2743
0
        deep = 0;
2744
2745
    /*
2746
     * First cleanup the automata removing cancelled transitions
2747
     */
2748
0
    for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2749
0
  state = ctxt->states[statenr];
2750
0
  if (state == NULL)
2751
0
      continue;
2752
0
  if (state->nbTrans < 2)
2753
0
      continue;
2754
0
  for (transnr = 0;transnr < state->nbTrans;transnr++) {
2755
0
      t1 = &(state->trans[transnr]);
2756
      /*
2757
       * Determinism checks in case of counted or all transitions
2758
       * will have to be handled separately
2759
       */
2760
0
      if (t1->atom == NULL) {
2761
    /* t1->nd = 1; */
2762
0
    continue;
2763
0
      }
2764
0
      if (t1->to < 0) /* eliminated */
2765
0
    continue;
2766
0
      for (i = 0;i < transnr;i++) {
2767
0
    t2 = &(state->trans[i]);
2768
0
    if (t2->to < 0) /* eliminated */
2769
0
        continue;
2770
0
    if (t2->atom != NULL) {
2771
0
        if (t1->to == t2->to) {
2772
                        /*
2773
                         * Here we use deep because we want to keep the
2774
                         * transitions which indicate a conflict
2775
                         */
2776
0
      if (xmlFAEqualAtoms(t1->atom, t2->atom, deep) &&
2777
0
                            (t1->counter == t2->counter) &&
2778
0
                            (t1->count == t2->count))
2779
0
          t2->to = -1; /* eliminated */
2780
0
        }
2781
0
    }
2782
0
      }
2783
0
  }
2784
0
    }
2785
2786
    /*
2787
     * Check for all states that there aren't 2 transitions
2788
     * with the same atom and a different target.
2789
     */
2790
0
    for (statenr = 0;statenr < ctxt->nbStates;statenr++) {
2791
0
  state = ctxt->states[statenr];
2792
0
  if (state == NULL)
2793
0
      continue;
2794
0
  if (state->nbTrans < 2)
2795
0
      continue;
2796
0
  last = NULL;
2797
0
  for (transnr = 0;transnr < state->nbTrans;transnr++) {
2798
0
      t1 = &(state->trans[transnr]);
2799
      /*
2800
       * Determinism checks in case of counted or all transitions
2801
       * will have to be handled separately
2802
       */
2803
0
      if (t1->atom == NULL) {
2804
0
    continue;
2805
0
      }
2806
0
      if (t1->to < 0) /* eliminated */
2807
0
    continue;
2808
0
      for (i = 0;i < transnr;i++) {
2809
0
    t2 = &(state->trans[i]);
2810
0
    if (t2->to < 0) /* eliminated */
2811
0
        continue;
2812
0
    if (t2->atom != NULL) {
2813
                    /*
2814
                     * But here we don't use deep because we want to
2815
                     * find transitions which indicate a conflict
2816
                     */
2817
0
        if (xmlFACompareAtoms(t1->atom, t2->atom, 1)) {
2818
                        /*
2819
                         * Treat equal counter transitions that couldn't be
2820
                         * eliminated as deterministic.
2821
                         */
2822
0
                        if ((t1->to != t2->to) ||
2823
0
                            (t1->counter == t2->counter) ||
2824
0
                            (!xmlFAEqualAtoms(t1->atom, t2->atom, deep)))
2825
0
                            ret = 0;
2826
      /* mark the transitions as non-deterministic ones */
2827
0
      t1->nd = 1;
2828
0
      t2->nd = 1;
2829
0
      last = t1;
2830
0
        }
2831
0
    } else {
2832
0
                    int res;
2833
2834
        /*
2835
         * do the closure in case of remaining specific
2836
         * epsilon transitions like choices or all
2837
         */
2838
0
        res = xmlFARecurseDeterminism(ctxt, ctxt->states[t2->to],
2839
0
              statenr, t1->to, t1->atom);
2840
0
                    xmlFAFinishRecurseDeterminism(ctxt, ctxt->states[t2->to]);
2841
        /* don't shortcut the computation so all non deterministic
2842
           transition get marked down
2843
        if (ret == 0)
2844
      return(0);
2845
         */
2846
0
        if (res == 0) {
2847
0
      t1->nd = 1;
2848
      /* t2->nd = 1; */
2849
0
      last = t1;
2850
0
                        ret = 0;
2851
0
        }
2852
0
    }
2853
0
      }
2854
      /* don't shortcut the computation so all non deterministic
2855
         transition get marked down
2856
      if (ret == 0)
2857
    break; */
2858
0
  }
2859
2860
  /*
2861
   * mark specifically the last non-deterministic transition
2862
   * from a state since there is no need to set-up rollback
2863
   * from it
2864
   */
2865
0
  if (last != NULL) {
2866
0
      last->nd = 2;
2867
0
  }
2868
2869
  /* don't shortcut the computation so all non deterministic
2870
     transition get marked down
2871
  if (ret == 0)
2872
      break; */
2873
0
    }
2874
2875
0
    ctxt->determinist = ret;
2876
0
    return(ret);
2877
0
}
2878
2879
/************************************************************************
2880
 *                  *
2881
 *  Routines to check input against transition atoms    *
2882
 *                  *
2883
 ************************************************************************/
2884
2885
static int
2886
xmlRegCheckCharacterRange(xmlRegAtomType type, int codepoint, int neg,
2887
0
                    int start, int end, const xmlChar *blockName) {
2888
0
    int ret = 0;
2889
2890
0
    switch (type) {
2891
0
        case XML_REGEXP_STRING:
2892
0
        case XML_REGEXP_SUBREG:
2893
0
        case XML_REGEXP_RANGES:
2894
0
        case XML_REGEXP_EPSILON:
2895
0
      return(-1);
2896
0
        case XML_REGEXP_ANYCHAR:
2897
0
      ret = ((codepoint != '\n') && (codepoint != '\r'));
2898
0
      break;
2899
0
        case XML_REGEXP_CHARVAL:
2900
0
      ret = ((codepoint >= start) && (codepoint <= end));
2901
0
      break;
2902
0
        case XML_REGEXP_NOTSPACE:
2903
0
      neg = !neg;
2904
            /* Falls through. */
2905
0
        case XML_REGEXP_ANYSPACE:
2906
0
      ret = ((codepoint == '\n') || (codepoint == '\r') ||
2907
0
       (codepoint == '\t') || (codepoint == ' '));
2908
0
      break;
2909
0
        case XML_REGEXP_NOTINITNAME:
2910
0
      neg = !neg;
2911
            /* Falls through. */
2912
0
        case XML_REGEXP_INITNAME:
2913
0
      ret = (IS_LETTER(codepoint) ||
2914
0
       (codepoint == '_') || (codepoint == ':'));
2915
0
      break;
2916
0
        case XML_REGEXP_NOTNAMECHAR:
2917
0
      neg = !neg;
2918
            /* Falls through. */
2919
0
        case XML_REGEXP_NAMECHAR:
2920
0
      ret = (IS_LETTER(codepoint) || IS_DIGIT(codepoint) ||
2921
0
       (codepoint == '.') || (codepoint == '-') ||
2922
0
       (codepoint == '_') || (codepoint == ':') ||
2923
0
       IS_COMBINING(codepoint) || IS_EXTENDER(codepoint));
2924
0
      break;
2925
0
        case XML_REGEXP_NOTDECIMAL:
2926
0
      neg = !neg;
2927
            /* Falls through. */
2928
0
        case XML_REGEXP_DECIMAL:
2929
0
      ret = xmlUCSIsCatNd(codepoint);
2930
0
      break;
2931
0
        case XML_REGEXP_REALCHAR:
2932
0
      neg = !neg;
2933
            /* Falls through. */
2934
0
        case XML_REGEXP_NOTREALCHAR:
2935
0
      ret = xmlUCSIsCatP(codepoint);
2936
0
      if (ret == 0)
2937
0
    ret = xmlUCSIsCatZ(codepoint);
2938
0
      if (ret == 0)
2939
0
    ret = xmlUCSIsCatC(codepoint);
2940
0
      break;
2941
0
        case XML_REGEXP_LETTER:
2942
0
      ret = xmlUCSIsCatL(codepoint);
2943
0
      break;
2944
0
        case XML_REGEXP_LETTER_UPPERCASE:
2945
0
      ret = xmlUCSIsCatLu(codepoint);
2946
0
      break;
2947
0
        case XML_REGEXP_LETTER_LOWERCASE:
2948
0
      ret = xmlUCSIsCatLl(codepoint);
2949
0
      break;
2950
0
        case XML_REGEXP_LETTER_TITLECASE:
2951
0
      ret = xmlUCSIsCatLt(codepoint);
2952
0
      break;
2953
0
        case XML_REGEXP_LETTER_MODIFIER:
2954
0
      ret = xmlUCSIsCatLm(codepoint);
2955
0
      break;
2956
0
        case XML_REGEXP_LETTER_OTHERS:
2957
0
      ret = xmlUCSIsCatLo(codepoint);
2958
0
      break;
2959
0
        case XML_REGEXP_MARK:
2960
0
      ret = xmlUCSIsCatM(codepoint);
2961
0
      break;
2962
0
        case XML_REGEXP_MARK_NONSPACING:
2963
0
      ret = xmlUCSIsCatMn(codepoint);
2964
0
      break;
2965
0
        case XML_REGEXP_MARK_SPACECOMBINING:
2966
0
      ret = xmlUCSIsCatMc(codepoint);
2967
0
      break;
2968
0
        case XML_REGEXP_MARK_ENCLOSING:
2969
0
      ret = xmlUCSIsCatMe(codepoint);
2970
0
      break;
2971
0
        case XML_REGEXP_NUMBER:
2972
0
      ret = xmlUCSIsCatN(codepoint);
2973
0
      break;
2974
0
        case XML_REGEXP_NUMBER_DECIMAL:
2975
0
      ret = xmlUCSIsCatNd(codepoint);
2976
0
      break;
2977
0
        case XML_REGEXP_NUMBER_LETTER:
2978
0
      ret = xmlUCSIsCatNl(codepoint);
2979
0
      break;
2980
0
        case XML_REGEXP_NUMBER_OTHERS:
2981
0
      ret = xmlUCSIsCatNo(codepoint);
2982
0
      break;
2983
0
        case XML_REGEXP_PUNCT:
2984
0
      ret = xmlUCSIsCatP(codepoint);
2985
0
      break;
2986
0
        case XML_REGEXP_PUNCT_CONNECTOR:
2987
0
      ret = xmlUCSIsCatPc(codepoint);
2988
0
      break;
2989
0
        case XML_REGEXP_PUNCT_DASH:
2990
0
      ret = xmlUCSIsCatPd(codepoint);
2991
0
      break;
2992
0
        case XML_REGEXP_PUNCT_OPEN:
2993
0
      ret = xmlUCSIsCatPs(codepoint);
2994
0
      break;
2995
0
        case XML_REGEXP_PUNCT_CLOSE:
2996
0
      ret = xmlUCSIsCatPe(codepoint);
2997
0
      break;
2998
0
        case XML_REGEXP_PUNCT_INITQUOTE:
2999
0
      ret = xmlUCSIsCatPi(codepoint);
3000
0
      break;
3001
0
        case XML_REGEXP_PUNCT_FINQUOTE:
3002
0
      ret = xmlUCSIsCatPf(codepoint);
3003
0
      break;
3004
0
        case XML_REGEXP_PUNCT_OTHERS:
3005
0
      ret = xmlUCSIsCatPo(codepoint);
3006
0
      break;
3007
0
        case XML_REGEXP_SEPAR:
3008
0
      ret = xmlUCSIsCatZ(codepoint);
3009
0
      break;
3010
0
        case XML_REGEXP_SEPAR_SPACE:
3011
0
      ret = xmlUCSIsCatZs(codepoint);
3012
0
      break;
3013
0
        case XML_REGEXP_SEPAR_LINE:
3014
0
      ret = xmlUCSIsCatZl(codepoint);
3015
0
      break;
3016
0
        case XML_REGEXP_SEPAR_PARA:
3017
0
      ret = xmlUCSIsCatZp(codepoint);
3018
0
      break;
3019
0
        case XML_REGEXP_SYMBOL:
3020
0
      ret = xmlUCSIsCatS(codepoint);
3021
0
      break;
3022
0
        case XML_REGEXP_SYMBOL_MATH:
3023
0
      ret = xmlUCSIsCatSm(codepoint);
3024
0
      break;
3025
0
        case XML_REGEXP_SYMBOL_CURRENCY:
3026
0
      ret = xmlUCSIsCatSc(codepoint);
3027
0
      break;
3028
0
        case XML_REGEXP_SYMBOL_MODIFIER:
3029
0
      ret = xmlUCSIsCatSk(codepoint);
3030
0
      break;
3031
0
        case XML_REGEXP_SYMBOL_OTHERS:
3032
0
      ret = xmlUCSIsCatSo(codepoint);
3033
0
      break;
3034
0
        case XML_REGEXP_OTHER:
3035
0
      ret = xmlUCSIsCatC(codepoint);
3036
0
      break;
3037
0
        case XML_REGEXP_OTHER_CONTROL:
3038
0
      ret = xmlUCSIsCatCc(codepoint);
3039
0
      break;
3040
0
        case XML_REGEXP_OTHER_FORMAT:
3041
0
      ret = xmlUCSIsCatCf(codepoint);
3042
0
      break;
3043
0
        case XML_REGEXP_OTHER_PRIVATE:
3044
0
      ret = xmlUCSIsCatCo(codepoint);
3045
0
      break;
3046
0
        case XML_REGEXP_OTHER_NA:
3047
      /* ret = xmlUCSIsCatCn(codepoint); */
3048
      /* Seems it doesn't exist anymore in recent Unicode releases */
3049
0
      ret = 0;
3050
0
      break;
3051
0
        case XML_REGEXP_BLOCK_NAME:
3052
0
      ret = xmlUCSIsBlock(codepoint, (const char *) blockName);
3053
0
      break;
3054
0
    }
3055
0
    if (neg)
3056
0
  return(!ret);
3057
0
    return(ret);
3058
0
}
3059
3060
static int
3061
0
xmlRegCheckCharacter(xmlRegAtomPtr atom, int codepoint) {
3062
0
    int i, ret = 0;
3063
0
    xmlRegRangePtr range;
3064
3065
0
    if ((atom == NULL) || (!IS_CHAR(codepoint)))
3066
0
  return(-1);
3067
3068
0
    switch (atom->type) {
3069
0
        case XML_REGEXP_SUBREG:
3070
0
        case XML_REGEXP_EPSILON:
3071
0
      return(-1);
3072
0
        case XML_REGEXP_CHARVAL:
3073
0
            return(codepoint == atom->codepoint);
3074
0
        case XML_REGEXP_RANGES: {
3075
0
      int accept = 0;
3076
3077
0
      for (i = 0;i < atom->nbRanges;i++) {
3078
0
    range = atom->ranges[i];
3079
0
    if (range->neg == 2) {
3080
0
        ret = xmlRegCheckCharacterRange(range->type, codepoint,
3081
0
            0, range->start, range->end,
3082
0
            range->blockName);
3083
0
        if (ret != 0)
3084
0
      return(0); /* excluded char */
3085
0
    } else if (range->neg) {
3086
0
        ret = xmlRegCheckCharacterRange(range->type, codepoint,
3087
0
            0, range->start, range->end,
3088
0
            range->blockName);
3089
0
        if (ret == 0)
3090
0
            accept = 1;
3091
0
        else
3092
0
            return(0);
3093
0
    } else {
3094
0
        ret = xmlRegCheckCharacterRange(range->type, codepoint,
3095
0
            0, range->start, range->end,
3096
0
            range->blockName);
3097
0
        if (ret != 0)
3098
0
      accept = 1; /* might still be excluded */
3099
0
    }
3100
0
      }
3101
0
      return(accept);
3102
0
  }
3103
0
        case XML_REGEXP_STRING:
3104
0
      printf("TODO: XML_REGEXP_STRING\n");
3105
0
      return(-1);
3106
0
        case XML_REGEXP_ANYCHAR:
3107
0
        case XML_REGEXP_ANYSPACE:
3108
0
        case XML_REGEXP_NOTSPACE:
3109
0
        case XML_REGEXP_INITNAME:
3110
0
        case XML_REGEXP_NOTINITNAME:
3111
0
        case XML_REGEXP_NAMECHAR:
3112
0
        case XML_REGEXP_NOTNAMECHAR:
3113
0
        case XML_REGEXP_DECIMAL:
3114
0
        case XML_REGEXP_NOTDECIMAL:
3115
0
        case XML_REGEXP_REALCHAR:
3116
0
        case XML_REGEXP_NOTREALCHAR:
3117
0
        case XML_REGEXP_LETTER:
3118
0
        case XML_REGEXP_LETTER_UPPERCASE:
3119
0
        case XML_REGEXP_LETTER_LOWERCASE:
3120
0
        case XML_REGEXP_LETTER_TITLECASE:
3121
0
        case XML_REGEXP_LETTER_MODIFIER:
3122
0
        case XML_REGEXP_LETTER_OTHERS:
3123
0
        case XML_REGEXP_MARK:
3124
0
        case XML_REGEXP_MARK_NONSPACING:
3125
0
        case XML_REGEXP_MARK_SPACECOMBINING:
3126
0
        case XML_REGEXP_MARK_ENCLOSING:
3127
0
        case XML_REGEXP_NUMBER:
3128
0
        case XML_REGEXP_NUMBER_DECIMAL:
3129
0
        case XML_REGEXP_NUMBER_LETTER:
3130
0
        case XML_REGEXP_NUMBER_OTHERS:
3131
0
        case XML_REGEXP_PUNCT:
3132
0
        case XML_REGEXP_PUNCT_CONNECTOR:
3133
0
        case XML_REGEXP_PUNCT_DASH:
3134
0
        case XML_REGEXP_PUNCT_OPEN:
3135
0
        case XML_REGEXP_PUNCT_CLOSE:
3136
0
        case XML_REGEXP_PUNCT_INITQUOTE:
3137
0
        case XML_REGEXP_PUNCT_FINQUOTE:
3138
0
        case XML_REGEXP_PUNCT_OTHERS:
3139
0
        case XML_REGEXP_SEPAR:
3140
0
        case XML_REGEXP_SEPAR_SPACE:
3141
0
        case XML_REGEXP_SEPAR_LINE:
3142
0
        case XML_REGEXP_SEPAR_PARA:
3143
0
        case XML_REGEXP_SYMBOL:
3144
0
        case XML_REGEXP_SYMBOL_MATH:
3145
0
        case XML_REGEXP_SYMBOL_CURRENCY:
3146
0
        case XML_REGEXP_SYMBOL_MODIFIER:
3147
0
        case XML_REGEXP_SYMBOL_OTHERS:
3148
0
        case XML_REGEXP_OTHER:
3149
0
        case XML_REGEXP_OTHER_CONTROL:
3150
0
        case XML_REGEXP_OTHER_FORMAT:
3151
0
        case XML_REGEXP_OTHER_PRIVATE:
3152
0
        case XML_REGEXP_OTHER_NA:
3153
0
  case XML_REGEXP_BLOCK_NAME:
3154
0
      ret = xmlRegCheckCharacterRange(atom->type, codepoint, 0, 0, 0,
3155
0
                                (const xmlChar *)atom->valuep);
3156
0
      if (atom->neg)
3157
0
    ret = !ret;
3158
0
      break;
3159
0
    }
3160
0
    return(ret);
3161
0
}
3162
3163
/************************************************************************
3164
 *                  *
3165
 *  Saving and restoring state of an execution context    *
3166
 *                  *
3167
 ************************************************************************/
3168
3169
#ifdef DEBUG_REGEXP_EXEC
3170
static void
3171
xmlFARegDebugExec(xmlRegExecCtxtPtr exec) {
3172
    printf("state: %d:%d:idx %d", exec->state->no, exec->transno, exec->index);
3173
    if (exec->inputStack != NULL) {
3174
  int i;
3175
  printf(": ");
3176
  for (i = 0;(i < 3) && (i < exec->inputStackNr);i++)
3177
      printf("%s ", (const char *)
3178
             exec->inputStack[exec->inputStackNr - (i + 1)].value);
3179
    } else {
3180
  printf(": %s", &(exec->inputString[exec->index]));
3181
    }
3182
    printf("\n");
3183
}
3184
#endif
3185
3186
static void
3187
0
xmlFARegExecSave(xmlRegExecCtxtPtr exec) {
3188
#ifdef DEBUG_REGEXP_EXEC
3189
    printf("saving ");
3190
    exec->transno++;
3191
    xmlFARegDebugExec(exec);
3192
    exec->transno--;
3193
#endif
3194
0
#ifdef MAX_PUSH
3195
0
    if (exec->nbPush > MAX_PUSH) {
3196
0
        return;
3197
0
    }
3198
0
    exec->nbPush++;
3199
0
#endif
3200
3201
0
    if (exec->maxRollbacks == 0) {
3202
0
  exec->maxRollbacks = 4;
3203
0
  exec->rollbacks = (xmlRegExecRollback *) xmlMalloc(exec->maxRollbacks *
3204
0
                                 sizeof(xmlRegExecRollback));
3205
0
  if (exec->rollbacks == NULL) {
3206
0
      xmlRegexpErrMemory(NULL, "saving regexp");
3207
0
      exec->maxRollbacks = 0;
3208
0
      return;
3209
0
  }
3210
0
  memset(exec->rollbacks, 0,
3211
0
         exec->maxRollbacks * sizeof(xmlRegExecRollback));
3212
0
    } else if (exec->nbRollbacks >= exec->maxRollbacks) {
3213
0
  xmlRegExecRollback *tmp;
3214
0
  int len = exec->maxRollbacks;
3215
3216
0
  exec->maxRollbacks *= 2;
3217
0
  tmp = (xmlRegExecRollback *) xmlRealloc(exec->rollbacks,
3218
0
      exec->maxRollbacks * sizeof(xmlRegExecRollback));
3219
0
  if (tmp == NULL) {
3220
0
      xmlRegexpErrMemory(NULL, "saving regexp");
3221
0
      exec->maxRollbacks /= 2;
3222
0
      return;
3223
0
  }
3224
0
  exec->rollbacks = tmp;
3225
0
  tmp = &exec->rollbacks[len];
3226
0
  memset(tmp, 0, (exec->maxRollbacks - len) * sizeof(xmlRegExecRollback));
3227
0
    }
3228
0
    exec->rollbacks[exec->nbRollbacks].state = exec->state;
3229
0
    exec->rollbacks[exec->nbRollbacks].index = exec->index;
3230
0
    exec->rollbacks[exec->nbRollbacks].nextbranch = exec->transno + 1;
3231
0
    if (exec->comp->nbCounters > 0) {
3232
0
  if (exec->rollbacks[exec->nbRollbacks].counts == NULL) {
3233
0
      exec->rollbacks[exec->nbRollbacks].counts = (int *)
3234
0
    xmlMalloc(exec->comp->nbCounters * sizeof(int));
3235
0
      if (exec->rollbacks[exec->nbRollbacks].counts == NULL) {
3236
0
    xmlRegexpErrMemory(NULL, "saving regexp");
3237
0
    exec->status = -5;
3238
0
    return;
3239
0
      }
3240
0
  }
3241
0
  memcpy(exec->rollbacks[exec->nbRollbacks].counts, exec->counts,
3242
0
         exec->comp->nbCounters * sizeof(int));
3243
0
    }
3244
0
    exec->nbRollbacks++;
3245
0
}
3246
3247
static void
3248
0
xmlFARegExecRollBack(xmlRegExecCtxtPtr exec) {
3249
0
    if (exec->nbRollbacks <= 0) {
3250
0
  exec->status = -1;
3251
#ifdef DEBUG_REGEXP_EXEC
3252
  printf("rollback failed on empty stack\n");
3253
#endif
3254
0
  return;
3255
0
    }
3256
0
    exec->nbRollbacks--;
3257
0
    exec->state = exec->rollbacks[exec->nbRollbacks].state;
3258
0
    exec->index = exec->rollbacks[exec->nbRollbacks].index;
3259
0
    exec->transno = exec->rollbacks[exec->nbRollbacks].nextbranch;
3260
0
    if (exec->comp->nbCounters > 0) {
3261
0
  if (exec->rollbacks[exec->nbRollbacks].counts == NULL) {
3262
0
      fprintf(stderr, "exec save: allocation failed");
3263
0
      exec->status = -6;
3264
0
      return;
3265
0
  }
3266
0
  if (exec->counts) {
3267
0
      memcpy(exec->counts, exec->rollbacks[exec->nbRollbacks].counts,
3268
0
         exec->comp->nbCounters * sizeof(int));
3269
0
  }
3270
0
    }
3271
3272
#ifdef DEBUG_REGEXP_EXEC
3273
    printf("restored ");
3274
    xmlFARegDebugExec(exec);
3275
#endif
3276
0
}
3277
3278
/************************************************************************
3279
 *                  *
3280
 *  Verifier, running an input against a compiled regexp    *
3281
 *                  *
3282
 ************************************************************************/
3283
3284
static int
3285
0
xmlFARegExec(xmlRegexpPtr comp, const xmlChar *content) {
3286
0
    xmlRegExecCtxt execval;
3287
0
    xmlRegExecCtxtPtr exec = &execval;
3288
0
    int ret, codepoint = 0, len, deter;
3289
3290
0
    exec->inputString = content;
3291
0
    exec->index = 0;
3292
0
    exec->nbPush = 0;
3293
0
    exec->determinist = 1;
3294
0
    exec->maxRollbacks = 0;
3295
0
    exec->nbRollbacks = 0;
3296
0
    exec->rollbacks = NULL;
3297
0
    exec->status = 0;
3298
0
    exec->comp = comp;
3299
0
    exec->state = comp->states[0];
3300
0
    exec->transno = 0;
3301
0
    exec->transcount = 0;
3302
0
    exec->inputStack = NULL;
3303
0
    exec->inputStackMax = 0;
3304
0
    if (comp->nbCounters > 0) {
3305
0
  exec->counts = (int *) xmlMalloc(comp->nbCounters * sizeof(int));
3306
0
  if (exec->counts == NULL) {
3307
0
      xmlRegexpErrMemory(NULL, "running regexp");
3308
0
      return(-1);
3309
0
  }
3310
0
        memset(exec->counts, 0, comp->nbCounters * sizeof(int));
3311
0
    } else
3312
0
  exec->counts = NULL;
3313
0
    while ((exec->status == 0) && (exec->state != NULL) &&
3314
0
     ((exec->inputString[exec->index] != 0) ||
3315
0
      ((exec->state != NULL) &&
3316
0
       (exec->state->type != XML_REGEXP_FINAL_STATE)))) {
3317
0
  xmlRegTransPtr trans;
3318
0
  xmlRegAtomPtr atom;
3319
3320
  /*
3321
   * If end of input on non-terminal state, rollback, however we may
3322
   * still have epsilon like transition for counted transitions
3323
   * on counters, in that case don't break too early.  Additionally,
3324
   * if we are working on a range like "AB{0,2}", where B is not present,
3325
   * we don't want to break.
3326
   */
3327
0
  len = 1;
3328
0
  if ((exec->inputString[exec->index] == 0) && (exec->counts == NULL)) {
3329
      /*
3330
       * if there is a transition, we must check if
3331
       *  atom allows minOccurs of 0
3332
       */
3333
0
      if (exec->transno < exec->state->nbTrans) {
3334
0
          trans = &exec->state->trans[exec->transno];
3335
0
    if (trans->to >=0) {
3336
0
        atom = trans->atom;
3337
0
        if (!((atom->min == 0) && (atom->max > 0)))
3338
0
            goto rollback;
3339
0
    }
3340
0
      } else
3341
0
          goto rollback;
3342
0
  }
3343
3344
0
  exec->transcount = 0;
3345
0
  for (;exec->transno < exec->state->nbTrans;exec->transno++) {
3346
0
      trans = &exec->state->trans[exec->transno];
3347
0
      if (trans->to < 0)
3348
0
    continue;
3349
0
      atom = trans->atom;
3350
0
      ret = 0;
3351
0
      deter = 1;
3352
0
      if (trans->count >= 0) {
3353
0
    int count;
3354
0
    xmlRegCounterPtr counter;
3355
3356
0
    if (exec->counts == NULL) {
3357
0
        exec->status = -1;
3358
0
        goto error;
3359
0
    }
3360
    /*
3361
     * A counted transition.
3362
     */
3363
3364
0
    count = exec->counts[trans->count];
3365
0
    counter = &exec->comp->counters[trans->count];
3366
#ifdef DEBUG_REGEXP_EXEC
3367
    printf("testing count %d: val %d, min %d, max %d\n",
3368
           trans->count, count, counter->min,  counter->max);
3369
#endif
3370
0
    ret = ((count >= counter->min) && (count <= counter->max));
3371
0
    if ((ret) && (counter->min != counter->max))
3372
0
        deter = 0;
3373
0
      } else if (atom == NULL) {
3374
0
    fprintf(stderr, "epsilon transition left at runtime\n");
3375
0
    exec->status = -2;
3376
0
    break;
3377
0
      } else if (exec->inputString[exec->index] != 0) {
3378
0
                codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len);
3379
0
    ret = xmlRegCheckCharacter(atom, codepoint);
3380
0
    if ((ret == 1) && (atom->min >= 0) && (atom->max > 0)) {
3381
0
        xmlRegStatePtr to = comp->states[trans->to];
3382
3383
        /*
3384
         * this is a multiple input sequence
3385
         * If there is a counter associated increment it now.
3386
         * do not increment if the counter is already over the
3387
         * maximum limit in which case get to next transition
3388
         */
3389
0
        if (trans->counter >= 0) {
3390
0
      xmlRegCounterPtr counter;
3391
3392
0
      if ((exec->counts == NULL) ||
3393
0
          (exec->comp == NULL) ||
3394
0
          (exec->comp->counters == NULL)) {
3395
0
          exec->status = -1;
3396
0
          goto error;
3397
0
      }
3398
0
      counter = &exec->comp->counters[trans->counter];
3399
0
      if (exec->counts[trans->counter] >= counter->max)
3400
0
          continue; /* for loop on transitions */
3401
0
                    }
3402
                    /* Save before incrementing */
3403
0
        if (exec->state->nbTrans > exec->transno + 1) {
3404
0
      xmlFARegExecSave(exec);
3405
0
        }
3406
0
        if (trans->counter >= 0) {
3407
#ifdef DEBUG_REGEXP_EXEC
3408
      printf("Increasing count %d\n", trans->counter);
3409
#endif
3410
0
      exec->counts[trans->counter]++;
3411
0
        }
3412
0
        exec->transcount = 1;
3413
0
        do {
3414
      /*
3415
       * Try to progress as much as possible on the input
3416
       */
3417
0
      if (exec->transcount == atom->max) {
3418
0
          break;
3419
0
      }
3420
0
      exec->index += len;
3421
      /*
3422
       * End of input: stop here
3423
       */
3424
0
      if (exec->inputString[exec->index] == 0) {
3425
0
          exec->index -= len;
3426
0
          break;
3427
0
      }
3428
0
      if (exec->transcount >= atom->min) {
3429
0
          int transno = exec->transno;
3430
0
          xmlRegStatePtr state = exec->state;
3431
3432
          /*
3433
           * The transition is acceptable save it
3434
           */
3435
0
          exec->transno = -1; /* trick */
3436
0
          exec->state = to;
3437
0
          xmlFARegExecSave(exec);
3438
0
          exec->transno = transno;
3439
0
          exec->state = state;
3440
0
      }
3441
0
      codepoint = CUR_SCHAR(&(exec->inputString[exec->index]),
3442
0
                      len);
3443
0
      ret = xmlRegCheckCharacter(atom, codepoint);
3444
0
      exec->transcount++;
3445
0
        } while (ret == 1);
3446
0
        if (exec->transcount < atom->min)
3447
0
      ret = 0;
3448
3449
        /*
3450
         * If the last check failed but one transition was found
3451
         * possible, rollback
3452
         */
3453
0
        if (ret < 0)
3454
0
      ret = 0;
3455
0
        if (ret == 0) {
3456
0
      goto rollback;
3457
0
        }
3458
0
        if (trans->counter >= 0) {
3459
0
      if (exec->counts == NULL) {
3460
0
          exec->status = -1;
3461
0
          goto error;
3462
0
      }
3463
#ifdef DEBUG_REGEXP_EXEC
3464
      printf("Decreasing count %d\n", trans->counter);
3465
#endif
3466
0
      exec->counts[trans->counter]--;
3467
0
        }
3468
0
    } else if ((ret == 0) && (atom->min == 0) && (atom->max > 0)) {
3469
        /*
3470
         * we don't match on the codepoint, but minOccurs of 0
3471
         * says that's ok.  Setting len to 0 inhibits stepping
3472
         * over the codepoint.
3473
         */
3474
0
        exec->transcount = 1;
3475
0
        len = 0;
3476
0
        ret = 1;
3477
0
    }
3478
0
      } else if ((atom->min == 0) && (atom->max > 0)) {
3479
          /* another spot to match when minOccurs is 0 */
3480
0
    exec->transcount = 1;
3481
0
    len = 0;
3482
0
    ret = 1;
3483
0
      }
3484
0
      if (ret == 1) {
3485
0
    if ((trans->nd == 1) ||
3486
0
        ((trans->count >= 0) && (deter == 0) &&
3487
0
         (exec->state->nbTrans > exec->transno + 1))) {
3488
#ifdef DEBUG_REGEXP_EXEC
3489
        if (trans->nd == 1)
3490
            printf("Saving on nd transition atom %d for %c at %d\n",
3491
             trans->atom->no, codepoint, exec->index);
3492
        else
3493
            printf("Saving on counted transition count %d for %c at %d\n",
3494
             trans->count, codepoint, exec->index);
3495
#endif
3496
0
        xmlFARegExecSave(exec);
3497
0
    }
3498
0
    if (trans->counter >= 0) {
3499
0
        xmlRegCounterPtr counter;
3500
3501
                    /* make sure we don't go over the counter maximum value */
3502
0
        if ((exec->counts == NULL) ||
3503
0
      (exec->comp == NULL) ||
3504
0
      (exec->comp->counters == NULL)) {
3505
0
      exec->status = -1;
3506
0
      goto error;
3507
0
        }
3508
0
        counter = &exec->comp->counters[trans->counter];
3509
0
        if (exec->counts[trans->counter] >= counter->max)
3510
0
      continue; /* for loop on transitions */
3511
#ifdef DEBUG_REGEXP_EXEC
3512
        printf("Increasing count %d\n", trans->counter);
3513
#endif
3514
0
        exec->counts[trans->counter]++;
3515
0
    }
3516
0
    if ((trans->count >= 0) &&
3517
0
        (trans->count < REGEXP_ALL_COUNTER)) {
3518
0
        if (exec->counts == NULL) {
3519
0
            exec->status = -1;
3520
0
      goto error;
3521
0
        }
3522
#ifdef DEBUG_REGEXP_EXEC
3523
        printf("resetting count %d on transition\n",
3524
               trans->count);
3525
#endif
3526
0
        exec->counts[trans->count] = 0;
3527
0
    }
3528
#ifdef DEBUG_REGEXP_EXEC
3529
    printf("entering state %d\n", trans->to);
3530
#endif
3531
0
    exec->state = comp->states[trans->to];
3532
0
    exec->transno = 0;
3533
0
    if (trans->atom != NULL) {
3534
0
        exec->index += len;
3535
0
    }
3536
0
    goto progress;
3537
0
      } else if (ret < 0) {
3538
0
    exec->status = -4;
3539
0
    break;
3540
0
      }
3541
0
  }
3542
0
  if ((exec->transno != 0) || (exec->state->nbTrans == 0)) {
3543
0
rollback:
3544
      /*
3545
       * Failed to find a way out
3546
       */
3547
0
      exec->determinist = 0;
3548
#ifdef DEBUG_REGEXP_EXEC
3549
      printf("rollback from state %d on %d:%c\n", exec->state->no,
3550
             codepoint,codepoint);
3551
#endif
3552
0
      xmlFARegExecRollBack(exec);
3553
0
  }
3554
0
progress:
3555
0
  continue;
3556
0
    }
3557
0
error:
3558
0
    if (exec->rollbacks != NULL) {
3559
0
  if (exec->counts != NULL) {
3560
0
      int i;
3561
3562
0
      for (i = 0;i < exec->maxRollbacks;i++)
3563
0
    if (exec->rollbacks[i].counts != NULL)
3564
0
        xmlFree(exec->rollbacks[i].counts);
3565
0
  }
3566
0
  xmlFree(exec->rollbacks);
3567
0
    }
3568
0
    if (exec->state == NULL)
3569
0
        return(-1);
3570
0
    if (exec->counts != NULL)
3571
0
  xmlFree(exec->counts);
3572
0
    if (exec->status == 0)
3573
0
  return(1);
3574
0
    if (exec->status == -1) {
3575
0
  if (exec->nbPush > MAX_PUSH)
3576
0
      return(-1);
3577
0
  return(0);
3578
0
    }
3579
0
    return(exec->status);
3580
0
}
3581
3582
/************************************************************************
3583
 *                  *
3584
 *  Progressive interface to the verifier one atom at a time  *
3585
 *                  *
3586
 ************************************************************************/
3587
#ifdef DEBUG_ERR
3588
static void testerr(xmlRegExecCtxtPtr exec);
3589
#endif
3590
3591
/**
3592
 * xmlRegNewExecCtxt:
3593
 * @comp: a precompiled regular expression
3594
 * @callback: a callback function used for handling progresses in the
3595
 *            automata matching phase
3596
 * @data: the context data associated to the callback in this context
3597
 *
3598
 * Build a context used for progressive evaluation of a regexp.
3599
 *
3600
 * Returns the new context
3601
 */
3602
xmlRegExecCtxtPtr
3603
0
xmlRegNewExecCtxt(xmlRegexpPtr comp, xmlRegExecCallbacks callback, void *data) {
3604
0
    xmlRegExecCtxtPtr exec;
3605
3606
0
    if (comp == NULL)
3607
0
  return(NULL);
3608
0
    if ((comp->compact == NULL) && (comp->states == NULL))
3609
0
        return(NULL);
3610
0
    exec = (xmlRegExecCtxtPtr) xmlMalloc(sizeof(xmlRegExecCtxt));
3611
0
    if (exec == NULL) {
3612
0
  xmlRegexpErrMemory(NULL, "creating execution context");
3613
0
  return(NULL);
3614
0
    }
3615
0
    memset(exec, 0, sizeof(xmlRegExecCtxt));
3616
0
    exec->inputString = NULL;
3617
0
    exec->index = 0;
3618
0
    exec->determinist = 1;
3619
0
    exec->maxRollbacks = 0;
3620
0
    exec->nbRollbacks = 0;
3621
0
    exec->rollbacks = NULL;
3622
0
    exec->status = 0;
3623
0
    exec->comp = comp;
3624
0
    if (comp->compact == NULL)
3625
0
  exec->state = comp->states[0];
3626
0
    exec->transno = 0;
3627
0
    exec->transcount = 0;
3628
0
    exec->callback = callback;
3629
0
    exec->data = data;
3630
0
    if (comp->nbCounters > 0) {
3631
        /*
3632
   * For error handling, exec->counts is allocated twice the size
3633
   * the second half is used to store the data in case of rollback
3634
   */
3635
0
  exec->counts = (int *) xmlMalloc(comp->nbCounters * sizeof(int)
3636
0
                                   * 2);
3637
0
  if (exec->counts == NULL) {
3638
0
      xmlRegexpErrMemory(NULL, "creating execution context");
3639
0
      xmlFree(exec);
3640
0
      return(NULL);
3641
0
  }
3642
0
        memset(exec->counts, 0, comp->nbCounters * sizeof(int) * 2);
3643
0
  exec->errCounts = &exec->counts[comp->nbCounters];
3644
0
    } else {
3645
0
  exec->counts = NULL;
3646
0
  exec->errCounts = NULL;
3647
0
    }
3648
0
    exec->inputStackMax = 0;
3649
0
    exec->inputStackNr = 0;
3650
0
    exec->inputStack = NULL;
3651
0
    exec->errStateNo = -1;
3652
0
    exec->errString = NULL;
3653
0
    exec->nbPush = 0;
3654
0
    return(exec);
3655
0
}
3656
3657
/**
3658
 * xmlRegFreeExecCtxt:
3659
 * @exec: a regular expression evaluation context
3660
 *
3661
 * Free the structures associated to a regular expression evaluation context.
3662
 */
3663
void
3664
0
xmlRegFreeExecCtxt(xmlRegExecCtxtPtr exec) {
3665
0
    if (exec == NULL)
3666
0
  return;
3667
3668
0
    if (exec->rollbacks != NULL) {
3669
0
  if (exec->counts != NULL) {
3670
0
      int i;
3671
3672
0
      for (i = 0;i < exec->maxRollbacks;i++)
3673
0
    if (exec->rollbacks[i].counts != NULL)
3674
0
        xmlFree(exec->rollbacks[i].counts);
3675
0
  }
3676
0
  xmlFree(exec->rollbacks);
3677
0
    }
3678
0
    if (exec->counts != NULL)
3679
0
  xmlFree(exec->counts);
3680
0
    if (exec->inputStack != NULL) {
3681
0
  int i;
3682
3683
0
  for (i = 0;i < exec->inputStackNr;i++) {
3684
0
      if (exec->inputStack[i].value != NULL)
3685
0
    xmlFree(exec->inputStack[i].value);
3686
0
  }
3687
0
  xmlFree(exec->inputStack);
3688
0
    }
3689
0
    if (exec->errString != NULL)
3690
0
        xmlFree(exec->errString);
3691
0
    xmlFree(exec);
3692
0
}
3693
3694
static void
3695
xmlFARegExecSaveInputString(xmlRegExecCtxtPtr exec, const xmlChar *value,
3696
0
                      void *data) {
3697
#ifdef DEBUG_PUSH
3698
    printf("saving value: %d:%s\n", exec->inputStackNr, value);
3699
#endif
3700
0
    if (exec->inputStackMax == 0) {
3701
0
  exec->inputStackMax = 4;
3702
0
  exec->inputStack = (xmlRegInputTokenPtr)
3703
0
      xmlMalloc(exec->inputStackMax * sizeof(xmlRegInputToken));
3704
0
  if (exec->inputStack == NULL) {
3705
0
      xmlRegexpErrMemory(NULL, "pushing input string");
3706
0
      exec->inputStackMax = 0;
3707
0
      return;
3708
0
  }
3709
0
    } else if (exec->inputStackNr + 1 >= exec->inputStackMax) {
3710
0
  xmlRegInputTokenPtr tmp;
3711
3712
0
  exec->inputStackMax *= 2;
3713
0
  tmp = (xmlRegInputTokenPtr) xmlRealloc(exec->inputStack,
3714
0
      exec->inputStackMax * sizeof(xmlRegInputToken));
3715
0
  if (tmp == NULL) {
3716
0
      xmlRegexpErrMemory(NULL, "pushing input string");
3717
0
      exec->inputStackMax /= 2;
3718
0
      return;
3719
0
  }
3720
0
  exec->inputStack = tmp;
3721
0
    }
3722
0
    exec->inputStack[exec->inputStackNr].value = xmlStrdup(value);
3723
0
    exec->inputStack[exec->inputStackNr].data = data;
3724
0
    exec->inputStackNr++;
3725
0
    exec->inputStack[exec->inputStackNr].value = NULL;
3726
0
    exec->inputStack[exec->inputStackNr].data = NULL;
3727
0
}
3728
3729
/**
3730
 * xmlRegStrEqualWildcard:
3731
 * @expStr:  the string to be evaluated
3732
 * @valStr:  the validation string
3733
 *
3734
 * Checks if both strings are equal or have the same content. "*"
3735
 * can be used as a wildcard in @valStr; "|" is used as a separator of
3736
 * substrings in both @expStr and @valStr.
3737
 *
3738
 * Returns 1 if the comparison is satisfied and the number of substrings
3739
 * is equal, 0 otherwise.
3740
 */
3741
3742
static int
3743
0
xmlRegStrEqualWildcard(const xmlChar *expStr, const xmlChar *valStr) {
3744
0
    if (expStr == valStr) return(1);
3745
0
    if (expStr == NULL) return(0);
3746
0
    if (valStr == NULL) return(0);
3747
0
    do {
3748
  /*
3749
  * Eval if we have a wildcard for the current item.
3750
  */
3751
0
        if (*expStr != *valStr) {
3752
      /* if one of them starts with a wildcard make valStr be it */
3753
0
      if (*valStr == '*') {
3754
0
          const xmlChar *tmp;
3755
3756
0
    tmp = valStr;
3757
0
    valStr = expStr;
3758
0
    expStr = tmp;
3759
0
      }
3760
0
      if ((*valStr != 0) && (*expStr != 0) && (*expStr++ == '*')) {
3761
0
    do {
3762
0
        if (*valStr == XML_REG_STRING_SEPARATOR)
3763
0
      break;
3764
0
        valStr++;
3765
0
    } while (*valStr != 0);
3766
0
    continue;
3767
0
      } else
3768
0
    return(0);
3769
0
  }
3770
0
  expStr++;
3771
0
  valStr++;
3772
0
    } while (*valStr != 0);
3773
0
    if (*expStr != 0)
3774
0
  return (0);
3775
0
    else
3776
0
  return (1);
3777
0
}
3778
3779
/**
3780
 * xmlRegCompactPushString:
3781
 * @exec: a regexp execution context
3782
 * @comp:  the precompiled exec with a compact table
3783
 * @value: a string token input
3784
 * @data: data associated to the token to reuse in callbacks
3785
 *
3786
 * Push one input token in the execution context
3787
 *
3788
 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
3789
 *     a negative value in case of error.
3790
 */
3791
static int
3792
xmlRegCompactPushString(xmlRegExecCtxtPtr exec,
3793
                  xmlRegexpPtr comp,
3794
                  const xmlChar *value,
3795
0
                  void *data) {
3796
0
    int state = exec->index;
3797
0
    int i, target;
3798
3799
0
    if ((comp == NULL) || (comp->compact == NULL) || (comp->stringMap == NULL))
3800
0
  return(-1);
3801
3802
0
    if (value == NULL) {
3803
  /*
3804
   * are we at a final state ?
3805
   */
3806
0
  if (comp->compact[state * (comp->nbstrings + 1)] ==
3807
0
            XML_REGEXP_FINAL_STATE)
3808
0
      return(1);
3809
0
  return(0);
3810
0
    }
3811
3812
#ifdef DEBUG_PUSH
3813
    printf("value pushed: %s\n", value);
3814
#endif
3815
3816
    /*
3817
     * Examine all outside transitions from current state
3818
     */
3819
0
    for (i = 0;i < comp->nbstrings;i++) {
3820
0
  target = comp->compact[state * (comp->nbstrings + 1) + i + 1];
3821
0
  if ((target > 0) && (target <= comp->nbstates)) {
3822
0
      target--; /* to avoid 0 */
3823
0
      if (xmlRegStrEqualWildcard(comp->stringMap[i], value)) {
3824
0
    exec->index = target;
3825
0
    if ((exec->callback != NULL) && (comp->transdata != NULL)) {
3826
0
        exec->callback(exec->data, value,
3827
0
        comp->transdata[state * comp->nbstrings + i], data);
3828
0
    }
3829
#ifdef DEBUG_PUSH
3830
    printf("entering state %d\n", target);
3831
#endif
3832
0
    if (comp->compact[target * (comp->nbstrings + 1)] ==
3833
0
        XML_REGEXP_SINK_STATE)
3834
0
        goto error;
3835
3836
0
    if (comp->compact[target * (comp->nbstrings + 1)] ==
3837
0
        XML_REGEXP_FINAL_STATE)
3838
0
        return(1);
3839
0
    return(0);
3840
0
      }
3841
0
  }
3842
0
    }
3843
    /*
3844
     * Failed to find an exit transition out from current state for the
3845
     * current token
3846
     */
3847
#ifdef DEBUG_PUSH
3848
    printf("failed to find a transition for %s on state %d\n", value, state);
3849
#endif
3850
0
error:
3851
0
    if (exec->errString != NULL)
3852
0
        xmlFree(exec->errString);
3853
0
    exec->errString = xmlStrdup(value);
3854
0
    exec->errStateNo = state;
3855
0
    exec->status = -1;
3856
#ifdef DEBUG_ERR
3857
    testerr(exec);
3858
#endif
3859
0
    return(-1);
3860
0
}
3861
3862
/**
3863
 * xmlRegExecPushStringInternal:
3864
 * @exec: a regexp execution context or NULL to indicate the end
3865
 * @value: a string token input
3866
 * @data: data associated to the token to reuse in callbacks
3867
 * @compound: value was assembled from 2 strings
3868
 *
3869
 * Push one input token in the execution context
3870
 *
3871
 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
3872
 *     a negative value in case of error.
3873
 */
3874
static int
3875
xmlRegExecPushStringInternal(xmlRegExecCtxtPtr exec, const xmlChar *value,
3876
0
                       void *data, int compound) {
3877
0
    xmlRegTransPtr trans;
3878
0
    xmlRegAtomPtr atom;
3879
0
    int ret;
3880
0
    int final = 0;
3881
0
    int progress = 1;
3882
3883
0
    if (exec == NULL)
3884
0
  return(-1);
3885
0
    if (exec->comp == NULL)
3886
0
  return(-1);
3887
0
    if (exec->status != 0)
3888
0
  return(exec->status);
3889
3890
0
    if (exec->comp->compact != NULL)
3891
0
  return(xmlRegCompactPushString(exec, exec->comp, value, data));
3892
3893
0
    if (value == NULL) {
3894
0
        if (exec->state->type == XML_REGEXP_FINAL_STATE)
3895
0
      return(1);
3896
0
  final = 1;
3897
0
    }
3898
3899
#ifdef DEBUG_PUSH
3900
    printf("value pushed: %s\n", value);
3901
#endif
3902
    /*
3903
     * If we have an active rollback stack push the new value there
3904
     * and get back to where we were left
3905
     */
3906
0
    if ((value != NULL) && (exec->inputStackNr > 0)) {
3907
0
  xmlFARegExecSaveInputString(exec, value, data);
3908
0
  value = exec->inputStack[exec->index].value;
3909
0
  data = exec->inputStack[exec->index].data;
3910
#ifdef DEBUG_PUSH
3911
  printf("value loaded: %s\n", value);
3912
#endif
3913
0
    }
3914
3915
0
    while ((exec->status == 0) &&
3916
0
     ((value != NULL) ||
3917
0
      ((final == 1) &&
3918
0
       (exec->state->type != XML_REGEXP_FINAL_STATE)))) {
3919
3920
  /*
3921
   * End of input on non-terminal state, rollback, however we may
3922
   * still have epsilon like transition for counted transitions
3923
   * on counters, in that case don't break too early.
3924
   */
3925
0
  if ((value == NULL) && (exec->counts == NULL))
3926
0
      goto rollback;
3927
3928
0
  exec->transcount = 0;
3929
0
  for (;exec->transno < exec->state->nbTrans;exec->transno++) {
3930
0
      trans = &exec->state->trans[exec->transno];
3931
0
      if (trans->to < 0)
3932
0
    continue;
3933
0
      atom = trans->atom;
3934
0
      ret = 0;
3935
0
      if (trans->count == REGEXP_ALL_LAX_COUNTER) {
3936
0
    int i;
3937
0
    int count;
3938
0
    xmlRegTransPtr t;
3939
0
    xmlRegCounterPtr counter;
3940
3941
0
    ret = 0;
3942
3943
#ifdef DEBUG_PUSH
3944
    printf("testing all lax %d\n", trans->count);
3945
#endif
3946
    /*
3947
     * Check all counted transitions from the current state
3948
     */
3949
0
    if ((value == NULL) && (final)) {
3950
0
        ret = 1;
3951
0
    } else if (value != NULL) {
3952
0
        for (i = 0;i < exec->state->nbTrans;i++) {
3953
0
      t = &exec->state->trans[i];
3954
0
      if ((t->counter < 0) || (t == trans))
3955
0
          continue;
3956
0
      counter = &exec->comp->counters[t->counter];
3957
0
      count = exec->counts[t->counter];
3958
0
      if ((count < counter->max) &&
3959
0
                (t->atom != NULL) &&
3960
0
          (xmlStrEqual(value, t->atom->valuep))) {
3961
0
          ret = 0;
3962
0
          break;
3963
0
      }
3964
0
      if ((count >= counter->min) &&
3965
0
          (count < counter->max) &&
3966
0
          (t->atom != NULL) &&
3967
0
          (xmlStrEqual(value, t->atom->valuep))) {
3968
0
          ret = 1;
3969
0
          break;
3970
0
      }
3971
0
        }
3972
0
    }
3973
0
      } else if (trans->count == REGEXP_ALL_COUNTER) {
3974
0
    int i;
3975
0
    int count;
3976
0
    xmlRegTransPtr t;
3977
0
    xmlRegCounterPtr counter;
3978
3979
0
    ret = 1;
3980
3981
#ifdef DEBUG_PUSH
3982
    printf("testing all %d\n", trans->count);
3983
#endif
3984
    /*
3985
     * Check all counted transitions from the current state
3986
     */
3987
0
    for (i = 0;i < exec->state->nbTrans;i++) {
3988
0
                    t = &exec->state->trans[i];
3989
0
        if ((t->counter < 0) || (t == trans))
3990
0
      continue;
3991
0
                    counter = &exec->comp->counters[t->counter];
3992
0
        count = exec->counts[t->counter];
3993
0
        if ((count < counter->min) || (count > counter->max)) {
3994
0
      ret = 0;
3995
0
      break;
3996
0
        }
3997
0
    }
3998
0
      } else if (trans->count >= 0) {
3999
0
    int count;
4000
0
    xmlRegCounterPtr counter;
4001
4002
    /*
4003
     * A counted transition.
4004
     */
4005
4006
0
    count = exec->counts[trans->count];
4007
0
    counter = &exec->comp->counters[trans->count];
4008
#ifdef DEBUG_PUSH
4009
    printf("testing count %d: val %d, min %d, max %d\n",
4010
           trans->count, count, counter->min,  counter->max);
4011
#endif
4012
0
    ret = ((count >= counter->min) && (count <= counter->max));
4013
0
      } else if (atom == NULL) {
4014
0
    fprintf(stderr, "epsilon transition left at runtime\n");
4015
0
    exec->status = -2;
4016
0
    break;
4017
0
      } else if (value != NULL) {
4018
0
    ret = xmlRegStrEqualWildcard(atom->valuep, value);
4019
0
    if (atom->neg) {
4020
0
        ret = !ret;
4021
0
        if (!compound)
4022
0
            ret = 0;
4023
0
    }
4024
0
    if ((ret == 1) && (trans->counter >= 0)) {
4025
0
        xmlRegCounterPtr counter;
4026
0
        int count;
4027
4028
0
        count = exec->counts[trans->counter];
4029
0
        counter = &exec->comp->counters[trans->counter];
4030
0
        if (count >= counter->max)
4031
0
      ret = 0;
4032
0
    }
4033
4034
0
    if ((ret == 1) && (atom->min > 0) && (atom->max > 0)) {
4035
0
        xmlRegStatePtr to = exec->comp->states[trans->to];
4036
4037
        /*
4038
         * this is a multiple input sequence
4039
         */
4040
0
        if (exec->state->nbTrans > exec->transno + 1) {
4041
0
      if (exec->inputStackNr <= 0) {
4042
0
          xmlFARegExecSaveInputString(exec, value, data);
4043
0
      }
4044
0
      xmlFARegExecSave(exec);
4045
0
        }
4046
0
        exec->transcount = 1;
4047
0
        do {
4048
      /*
4049
       * Try to progress as much as possible on the input
4050
       */
4051
0
      if (exec->transcount == atom->max) {
4052
0
          break;
4053
0
      }
4054
0
      exec->index++;
4055
0
      value = exec->inputStack[exec->index].value;
4056
0
      data = exec->inputStack[exec->index].data;
4057
#ifdef DEBUG_PUSH
4058
      printf("value loaded: %s\n", value);
4059
#endif
4060
4061
      /*
4062
       * End of input: stop here
4063
       */
4064
0
      if (value == NULL) {
4065
0
          exec->index --;
4066
0
          break;
4067
0
      }
4068
0
      if (exec->transcount >= atom->min) {
4069
0
          int transno = exec->transno;
4070
0
          xmlRegStatePtr state = exec->state;
4071
4072
          /*
4073
           * The transition is acceptable save it
4074
           */
4075
0
          exec->transno = -1; /* trick */
4076
0
          exec->state = to;
4077
0
          if (exec->inputStackNr <= 0) {
4078
0
        xmlFARegExecSaveInputString(exec, value, data);
4079
0
          }
4080
0
          xmlFARegExecSave(exec);
4081
0
          exec->transno = transno;
4082
0
          exec->state = state;
4083
0
      }
4084
0
      ret = xmlStrEqual(value, atom->valuep);
4085
0
      exec->transcount++;
4086
0
        } while (ret == 1);
4087
0
        if (exec->transcount < atom->min)
4088
0
      ret = 0;
4089
4090
        /*
4091
         * If the last check failed but one transition was found
4092
         * possible, rollback
4093
         */
4094
0
        if (ret < 0)
4095
0
      ret = 0;
4096
0
        if (ret == 0) {
4097
0
      goto rollback;
4098
0
        }
4099
0
    }
4100
0
      }
4101
0
      if (ret == 1) {
4102
0
    if ((exec->callback != NULL) && (atom != NULL) &&
4103
0
      (data != NULL)) {
4104
0
        exec->callback(exec->data, atom->valuep,
4105
0
                 atom->data, data);
4106
0
    }
4107
0
    if (exec->state->nbTrans > exec->transno + 1) {
4108
0
        if (exec->inputStackNr <= 0) {
4109
0
      xmlFARegExecSaveInputString(exec, value, data);
4110
0
        }
4111
0
        xmlFARegExecSave(exec);
4112
0
    }
4113
0
    if (trans->counter >= 0) {
4114
#ifdef DEBUG_PUSH
4115
        printf("Increasing count %d\n", trans->counter);
4116
#endif
4117
0
        exec->counts[trans->counter]++;
4118
0
    }
4119
0
    if ((trans->count >= 0) &&
4120
0
        (trans->count < REGEXP_ALL_COUNTER)) {
4121
#ifdef DEBUG_REGEXP_EXEC
4122
        printf("resetting count %d on transition\n",
4123
               trans->count);
4124
#endif
4125
0
        exec->counts[trans->count] = 0;
4126
0
    }
4127
#ifdef DEBUG_PUSH
4128
    printf("entering state %d\n", trans->to);
4129
#endif
4130
0
                if ((exec->comp->states[trans->to] != NULL) &&
4131
0
        (exec->comp->states[trans->to]->type ==
4132
0
         XML_REGEXP_SINK_STATE)) {
4133
        /*
4134
         * entering a sink state, save the current state as error
4135
         * state.
4136
         */
4137
0
        if (exec->errString != NULL)
4138
0
      xmlFree(exec->errString);
4139
0
        exec->errString = xmlStrdup(value);
4140
0
        exec->errState = exec->state;
4141
0
        memcpy(exec->errCounts, exec->counts,
4142
0
         exec->comp->nbCounters * sizeof(int));
4143
0
    }
4144
0
    exec->state = exec->comp->states[trans->to];
4145
0
    exec->transno = 0;
4146
0
    if (trans->atom != NULL) {
4147
0
        if (exec->inputStack != NULL) {
4148
0
      exec->index++;
4149
0
      if (exec->index < exec->inputStackNr) {
4150
0
          value = exec->inputStack[exec->index].value;
4151
0
          data = exec->inputStack[exec->index].data;
4152
#ifdef DEBUG_PUSH
4153
          printf("value loaded: %s\n", value);
4154
#endif
4155
0
      } else {
4156
0
          value = NULL;
4157
0
          data = NULL;
4158
#ifdef DEBUG_PUSH
4159
          printf("end of input\n");
4160
#endif
4161
0
      }
4162
0
        } else {
4163
0
      value = NULL;
4164
0
      data = NULL;
4165
#ifdef DEBUG_PUSH
4166
      printf("end of input\n");
4167
#endif
4168
0
        }
4169
0
    }
4170
0
    goto progress;
4171
0
      } else if (ret < 0) {
4172
0
    exec->status = -4;
4173
0
    break;
4174
0
      }
4175
0
  }
4176
0
  if ((exec->transno != 0) || (exec->state->nbTrans == 0)) {
4177
0
rollback:
4178
            /*
4179
       * if we didn't yet rollback on the current input
4180
       * store the current state as the error state.
4181
       */
4182
0
      if ((progress) && (exec->state != NULL) &&
4183
0
          (exec->state->type != XML_REGEXP_SINK_STATE)) {
4184
0
          progress = 0;
4185
0
    if (exec->errString != NULL)
4186
0
        xmlFree(exec->errString);
4187
0
    exec->errString = xmlStrdup(value);
4188
0
    exec->errState = exec->state;
4189
0
                if (exec->comp->nbCounters)
4190
0
                    memcpy(exec->errCounts, exec->counts,
4191
0
                           exec->comp->nbCounters * sizeof(int));
4192
0
      }
4193
4194
      /*
4195
       * Failed to find a way out
4196
       */
4197
0
      exec->determinist = 0;
4198
0
      xmlFARegExecRollBack(exec);
4199
0
      if ((exec->inputStack != NULL ) && (exec->status == 0)) {
4200
0
    value = exec->inputStack[exec->index].value;
4201
0
    data = exec->inputStack[exec->index].data;
4202
#ifdef DEBUG_PUSH
4203
    printf("value loaded: %s\n", value);
4204
#endif
4205
0
      }
4206
0
  }
4207
0
  continue;
4208
0
progress:
4209
0
        progress = 1;
4210
0
  continue;
4211
0
    }
4212
0
    if (exec->status == 0) {
4213
0
        return(exec->state->type == XML_REGEXP_FINAL_STATE);
4214
0
    }
4215
#ifdef DEBUG_ERR
4216
    if (exec->status < 0) {
4217
  testerr(exec);
4218
    }
4219
#endif
4220
0
    return(exec->status);
4221
0
}
4222
4223
/**
4224
 * xmlRegExecPushString:
4225
 * @exec: a regexp execution context or NULL to indicate the end
4226
 * @value: a string token input
4227
 * @data: data associated to the token to reuse in callbacks
4228
 *
4229
 * Push one input token in the execution context
4230
 *
4231
 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
4232
 *     a negative value in case of error.
4233
 */
4234
int
4235
xmlRegExecPushString(xmlRegExecCtxtPtr exec, const xmlChar *value,
4236
0
               void *data) {
4237
0
    return(xmlRegExecPushStringInternal(exec, value, data, 0));
4238
0
}
4239
4240
/**
4241
 * xmlRegExecPushString2:
4242
 * @exec: a regexp execution context or NULL to indicate the end
4243
 * @value: the first string token input
4244
 * @value2: the second string token input
4245
 * @data: data associated to the token to reuse in callbacks
4246
 *
4247
 * Push one input token in the execution context
4248
 *
4249
 * Returns: 1 if the regexp reached a final state, 0 if non-final, and
4250
 *     a negative value in case of error.
4251
 */
4252
int
4253
xmlRegExecPushString2(xmlRegExecCtxtPtr exec, const xmlChar *value,
4254
0
                      const xmlChar *value2, void *data) {
4255
0
    xmlChar buf[150];
4256
0
    int lenn, lenp, ret;
4257
0
    xmlChar *str;
4258
4259
0
    if (exec == NULL)
4260
0
  return(-1);
4261
0
    if (exec->comp == NULL)
4262
0
  return(-1);
4263
0
    if (exec->status != 0)
4264
0
  return(exec->status);
4265
4266
0
    if (value2 == NULL)
4267
0
        return(xmlRegExecPushString(exec, value, data));
4268
4269
0
    lenn = strlen((char *) value2);
4270
0
    lenp = strlen((char *) value);
4271
4272
0
    if (150 < lenn + lenp + 2) {
4273
0
  str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
4274
0
  if (str == NULL) {
4275
0
      exec->status = -1;
4276
0
      return(-1);
4277
0
  }
4278
0
    } else {
4279
0
  str = buf;
4280
0
    }
4281
0
    memcpy(&str[0], value, lenp);
4282
0
    str[lenp] = XML_REG_STRING_SEPARATOR;
4283
0
    memcpy(&str[lenp + 1], value2, lenn);
4284
0
    str[lenn + lenp + 1] = 0;
4285
4286
0
    if (exec->comp->compact != NULL)
4287
0
  ret = xmlRegCompactPushString(exec, exec->comp, str, data);
4288
0
    else
4289
0
        ret = xmlRegExecPushStringInternal(exec, str, data, 1);
4290
4291
0
    if (str != buf)
4292
0
        xmlFree(str);
4293
0
    return(ret);
4294
0
}
4295
4296
/**
4297
 * xmlRegExecGetValues:
4298
 * @exec: a regexp execution context
4299
 * @err: error extraction or normal one
4300
 * @nbval: pointer to the number of accepted values IN/OUT
4301
 * @nbneg: return number of negative transitions
4302
 * @values: pointer to the array of acceptable values
4303
 * @terminal: return value if this was a terminal state
4304
 *
4305
 * Extract information from the regexp execution, internal routine to
4306
 * implement xmlRegExecNextValues() and xmlRegExecErrInfo()
4307
 *
4308
 * Returns: 0 in case of success or -1 in case of error.
4309
 */
4310
static int
4311
xmlRegExecGetValues(xmlRegExecCtxtPtr exec, int err,
4312
                    int *nbval, int *nbneg,
4313
0
        xmlChar **values, int *terminal) {
4314
0
    int maxval;
4315
0
    int nb = 0;
4316
4317
0
    if ((exec == NULL) || (nbval == NULL) || (nbneg == NULL) ||
4318
0
        (values == NULL) || (*nbval <= 0))
4319
0
        return(-1);
4320
4321
0
    maxval = *nbval;
4322
0
    *nbval = 0;
4323
0
    *nbneg = 0;
4324
0
    if ((exec->comp != NULL) && (exec->comp->compact != NULL)) {
4325
0
        xmlRegexpPtr comp;
4326
0
  int target, i, state;
4327
4328
0
        comp = exec->comp;
4329
4330
0
  if (err) {
4331
0
      if (exec->errStateNo == -1) return(-1);
4332
0
      state = exec->errStateNo;
4333
0
  } else {
4334
0
      state = exec->index;
4335
0
  }
4336
0
  if (terminal != NULL) {
4337
0
      if (comp->compact[state * (comp->nbstrings + 1)] ==
4338
0
          XML_REGEXP_FINAL_STATE)
4339
0
    *terminal = 1;
4340
0
      else
4341
0
    *terminal = 0;
4342
0
  }
4343
0
  for (i = 0;(i < comp->nbstrings) && (nb < maxval);i++) {
4344
0
      target = comp->compact[state * (comp->nbstrings + 1) + i + 1];
4345
0
      if ((target > 0) && (target <= comp->nbstates) &&
4346
0
          (comp->compact[(target - 1) * (comp->nbstrings + 1)] !=
4347
0
     XML_REGEXP_SINK_STATE)) {
4348
0
          values[nb++] = comp->stringMap[i];
4349
0
    (*nbval)++;
4350
0
      }
4351
0
  }
4352
0
  for (i = 0;(i < comp->nbstrings) && (nb < maxval);i++) {
4353
0
      target = comp->compact[state * (comp->nbstrings + 1) + i + 1];
4354
0
      if ((target > 0) && (target <= comp->nbstates) &&
4355
0
          (comp->compact[(target - 1) * (comp->nbstrings + 1)] ==
4356
0
     XML_REGEXP_SINK_STATE)) {
4357
0
          values[nb++] = comp->stringMap[i];
4358
0
    (*nbneg)++;
4359
0
      }
4360
0
  }
4361
0
    } else {
4362
0
        int transno;
4363
0
  xmlRegTransPtr trans;
4364
0
  xmlRegAtomPtr atom;
4365
0
  xmlRegStatePtr state;
4366
4367
0
  if (terminal != NULL) {
4368
0
      if (exec->state->type == XML_REGEXP_FINAL_STATE)
4369
0
    *terminal = 1;
4370
0
      else
4371
0
    *terminal = 0;
4372
0
  }
4373
4374
0
  if (err) {
4375
0
      if (exec->errState == NULL) return(-1);
4376
0
      state = exec->errState;
4377
0
  } else {
4378
0
      if (exec->state == NULL) return(-1);
4379
0
      state = exec->state;
4380
0
  }
4381
0
  for (transno = 0;
4382
0
       (transno < state->nbTrans) && (nb < maxval);
4383
0
       transno++) {
4384
0
      trans = &state->trans[transno];
4385
0
      if (trans->to < 0)
4386
0
    continue;
4387
0
      atom = trans->atom;
4388
0
      if ((atom == NULL) || (atom->valuep == NULL))
4389
0
    continue;
4390
0
      if (trans->count == REGEXP_ALL_LAX_COUNTER) {
4391
          /* this should not be reached but ... */
4392
0
          TODO;
4393
0
      } else if (trans->count == REGEXP_ALL_COUNTER) {
4394
          /* this should not be reached but ... */
4395
0
          TODO;
4396
0
      } else if (trans->counter >= 0) {
4397
0
    xmlRegCounterPtr counter = NULL;
4398
0
    int count;
4399
4400
0
    if (err)
4401
0
        count = exec->errCounts[trans->counter];
4402
0
    else
4403
0
        count = exec->counts[trans->counter];
4404
0
    if (exec->comp != NULL)
4405
0
        counter = &exec->comp->counters[trans->counter];
4406
0
    if ((counter == NULL) || (count < counter->max)) {
4407
0
        if (atom->neg)
4408
0
      values[nb++] = (xmlChar *) atom->valuep2;
4409
0
        else
4410
0
      values[nb++] = (xmlChar *) atom->valuep;
4411
0
        (*nbval)++;
4412
0
    }
4413
0
      } else {
4414
0
                if ((exec->comp != NULL) && (exec->comp->states[trans->to] != NULL) &&
4415
0
        (exec->comp->states[trans->to]->type !=
4416
0
         XML_REGEXP_SINK_STATE)) {
4417
0
        if (atom->neg)
4418
0
      values[nb++] = (xmlChar *) atom->valuep2;
4419
0
        else
4420
0
      values[nb++] = (xmlChar *) atom->valuep;
4421
0
        (*nbval)++;
4422
0
    }
4423
0
      }
4424
0
  }
4425
0
  for (transno = 0;
4426
0
       (transno < state->nbTrans) && (nb < maxval);
4427
0
       transno++) {
4428
0
      trans = &state->trans[transno];
4429
0
      if (trans->to < 0)
4430
0
    continue;
4431
0
      atom = trans->atom;
4432
0
      if ((atom == NULL) || (atom->valuep == NULL))
4433
0
    continue;
4434
0
      if (trans->count == REGEXP_ALL_LAX_COUNTER) {
4435
0
          continue;
4436
0
      } else if (trans->count == REGEXP_ALL_COUNTER) {
4437
0
          continue;
4438
0
      } else if (trans->counter >= 0) {
4439
0
          continue;
4440
0
      } else {
4441
0
                if ((exec->comp->states[trans->to] != NULL) &&
4442
0
        (exec->comp->states[trans->to]->type ==
4443
0
         XML_REGEXP_SINK_STATE)) {
4444
0
        if (atom->neg)
4445
0
      values[nb++] = (xmlChar *) atom->valuep2;
4446
0
        else
4447
0
      values[nb++] = (xmlChar *) atom->valuep;
4448
0
        (*nbneg)++;
4449
0
    }
4450
0
      }
4451
0
  }
4452
0
    }
4453
0
    return(0);
4454
0
}
4455
4456
/**
4457
 * xmlRegExecNextValues:
4458
 * @exec: a regexp execution context
4459
 * @nbval: pointer to the number of accepted values IN/OUT
4460
 * @nbneg: return number of negative transitions
4461
 * @values: pointer to the array of acceptable values
4462
 * @terminal: return value if this was a terminal state
4463
 *
4464
 * Extract information from the regexp execution,
4465
 * the parameter @values must point to an array of @nbval string pointers
4466
 * on return nbval will contain the number of possible strings in that
4467
 * state and the @values array will be updated with them. The string values
4468
 * returned will be freed with the @exec context and don't need to be
4469
 * deallocated.
4470
 *
4471
 * Returns: 0 in case of success or -1 in case of error.
4472
 */
4473
int
4474
xmlRegExecNextValues(xmlRegExecCtxtPtr exec, int *nbval, int *nbneg,
4475
0
                     xmlChar **values, int *terminal) {
4476
0
    return(xmlRegExecGetValues(exec, 0, nbval, nbneg, values, terminal));
4477
0
}
4478
4479
/**
4480
 * xmlRegExecErrInfo:
4481
 * @exec: a regexp execution context generating an error
4482
 * @string: return value for the error string
4483
 * @nbval: pointer to the number of accepted values IN/OUT
4484
 * @nbneg: return number of negative transitions
4485
 * @values: pointer to the array of acceptable values
4486
 * @terminal: return value if this was a terminal state
4487
 *
4488
 * Extract error information from the regexp execution, the parameter
4489
 * @string will be updated with the value pushed and not accepted,
4490
 * the parameter @values must point to an array of @nbval string pointers
4491
 * on return nbval will contain the number of possible strings in that
4492
 * state and the @values array will be updated with them. The string values
4493
 * returned will be freed with the @exec context and don't need to be
4494
 * deallocated.
4495
 *
4496
 * Returns: 0 in case of success or -1 in case of error.
4497
 */
4498
int
4499
xmlRegExecErrInfo(xmlRegExecCtxtPtr exec, const xmlChar **string,
4500
0
                  int *nbval, int *nbneg, xmlChar **values, int *terminal) {
4501
0
    if (exec == NULL)
4502
0
        return(-1);
4503
0
    if (string != NULL) {
4504
0
        if (exec->status != 0)
4505
0
      *string = exec->errString;
4506
0
  else
4507
0
      *string = NULL;
4508
0
    }
4509
0
    return(xmlRegExecGetValues(exec, 1, nbval, nbneg, values, terminal));
4510
0
}
4511
4512
#ifdef DEBUG_ERR
4513
static void testerr(xmlRegExecCtxtPtr exec) {
4514
    const xmlChar *string;
4515
    xmlChar *values[5];
4516
    int nb = 5;
4517
    int nbneg;
4518
    int terminal;
4519
    xmlRegExecErrInfo(exec, &string, &nb, &nbneg, &values[0], &terminal);
4520
}
4521
#endif
4522
4523
#if 0
4524
static int
4525
xmlRegExecPushChar(xmlRegExecCtxtPtr exec, int UCS) {
4526
    xmlRegTransPtr trans;
4527
    xmlRegAtomPtr atom;
4528
    int ret;
4529
    int codepoint, len;
4530
4531
    if (exec == NULL)
4532
  return(-1);
4533
    if (exec->status != 0)
4534
  return(exec->status);
4535
4536
    while ((exec->status == 0) &&
4537
     ((exec->inputString[exec->index] != 0) ||
4538
      (exec->state->type != XML_REGEXP_FINAL_STATE))) {
4539
4540
  /*
4541
   * End of input on non-terminal state, rollback, however we may
4542
   * still have epsilon like transition for counted transitions
4543
   * on counters, in that case don't break too early.
4544
   */
4545
  if ((exec->inputString[exec->index] == 0) && (exec->counts == NULL))
4546
      goto rollback;
4547
4548
  exec->transcount = 0;
4549
  for (;exec->transno < exec->state->nbTrans;exec->transno++) {
4550
      trans = &exec->state->trans[exec->transno];
4551
      if (trans->to < 0)
4552
    continue;
4553
      atom = trans->atom;
4554
      ret = 0;
4555
      if (trans->count >= 0) {
4556
    int count;
4557
    xmlRegCounterPtr counter;
4558
4559
    /*
4560
     * A counted transition.
4561
     */
4562
4563
    count = exec->counts[trans->count];
4564
    counter = &exec->comp->counters[trans->count];
4565
#ifdef DEBUG_REGEXP_EXEC
4566
    printf("testing count %d: val %d, min %d, max %d\n",
4567
           trans->count, count, counter->min,  counter->max);
4568
#endif
4569
    ret = ((count >= counter->min) && (count <= counter->max));
4570
      } else if (atom == NULL) {
4571
    fprintf(stderr, "epsilon transition left at runtime\n");
4572
    exec->status = -2;
4573
    break;
4574
      } else if (exec->inputString[exec->index] != 0) {
4575
                codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len);
4576
    ret = xmlRegCheckCharacter(atom, codepoint);
4577
    if ((ret == 1) && (atom->min > 0) && (atom->max > 0)) {
4578
        xmlRegStatePtr to = exec->comp->states[trans->to];
4579
4580
        /*
4581
         * this is a multiple input sequence
4582
         */
4583
        if (exec->state->nbTrans > exec->transno + 1) {
4584
      xmlFARegExecSave(exec);
4585
        }
4586
        exec->transcount = 1;
4587
        do {
4588
      /*
4589
       * Try to progress as much as possible on the input
4590
       */
4591
      if (exec->transcount == atom->max) {
4592
          break;
4593
      }
4594
      exec->index += len;
4595
      /*
4596
       * End of input: stop here
4597
       */
4598
      if (exec->inputString[exec->index] == 0) {
4599
          exec->index -= len;
4600
          break;
4601
      }
4602
      if (exec->transcount >= atom->min) {
4603
          int transno = exec->transno;
4604
          xmlRegStatePtr state = exec->state;
4605
4606
          /*
4607
           * The transition is acceptable save it
4608
           */
4609
          exec->transno = -1; /* trick */
4610
          exec->state = to;
4611
          xmlFARegExecSave(exec);
4612
          exec->transno = transno;
4613
          exec->state = state;
4614
      }
4615
      codepoint = CUR_SCHAR(&(exec->inputString[exec->index]),
4616
                      len);
4617
      ret = xmlRegCheckCharacter(atom, codepoint);
4618
      exec->transcount++;
4619
        } while (ret == 1);
4620
        if (exec->transcount < atom->min)
4621
      ret = 0;
4622
4623
        /*
4624
         * If the last check failed but one transition was found
4625
         * possible, rollback
4626
         */
4627
        if (ret < 0)
4628
      ret = 0;
4629
        if (ret == 0) {
4630
      goto rollback;
4631
        }
4632
    }
4633
      }
4634
      if (ret == 1) {
4635
    if (exec->state->nbTrans > exec->transno + 1) {
4636
        xmlFARegExecSave(exec);
4637
    }
4638
    /*
4639
     * restart count for expressions like this ((abc){2})*
4640
     */
4641
    if (trans->count >= 0) {
4642
#ifdef DEBUG_REGEXP_EXEC
4643
        printf("Reset count %d\n", trans->count);
4644
#endif
4645
        exec->counts[trans->count] = 0;
4646
    }
4647
    if (trans->counter >= 0) {
4648
#ifdef DEBUG_REGEXP_EXEC
4649
        printf("Increasing count %d\n", trans->counter);
4650
#endif
4651
        exec->counts[trans->counter]++;
4652
    }
4653
#ifdef DEBUG_REGEXP_EXEC
4654
    printf("entering state %d\n", trans->to);
4655
#endif
4656
    exec->state = exec->comp->states[trans->to];
4657
    exec->transno = 0;
4658
    if (trans->atom != NULL) {
4659
        exec->index += len;
4660
    }
4661
    goto progress;
4662
      } else if (ret < 0) {
4663
    exec->status = -4;
4664
    break;
4665
      }
4666
  }
4667
  if ((exec->transno != 0) || (exec->state->nbTrans == 0)) {
4668
rollback:
4669
      /*
4670
       * Failed to find a way out
4671
       */
4672
      exec->determinist = 0;
4673
      xmlFARegExecRollBack(exec);
4674
  }
4675
progress:
4676
  continue;
4677
    }
4678
}
4679
#endif
4680
/************************************************************************
4681
 *                  *
4682
 *  Parser for the Schemas Datatype Regular Expressions   *
4683
 *  http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#regexs  *
4684
 *                  *
4685
 ************************************************************************/
4686
4687
/**
4688
 * xmlFAIsChar:
4689
 * @ctxt:  a regexp parser context
4690
 *
4691
 * [10]   Char   ::=   [^.\?*+()|#x5B#x5D]
4692
 */
4693
static int
4694
0
xmlFAIsChar(xmlRegParserCtxtPtr ctxt) {
4695
0
    int cur;
4696
0
    int len;
4697
4698
0
    cur = CUR_SCHAR(ctxt->cur, len);
4699
0
    if ((cur == '.') || (cur == '\\') || (cur == '?') ||
4700
0
  (cur == '*') || (cur == '+') || (cur == '(') ||
4701
0
  (cur == ')') || (cur == '|') || (cur == 0x5B) ||
4702
0
  (cur == 0x5D) || (cur == 0))
4703
0
  return(-1);
4704
0
    return(cur);
4705
0
}
4706
4707
/**
4708
 * xmlFAParseCharProp:
4709
 * @ctxt:  a regexp parser context
4710
 *
4711
 * [27]   charProp   ::=   IsCategory | IsBlock
4712
 * [28]   IsCategory ::= Letters | Marks | Numbers | Punctuation |
4713
 *                       Separators | Symbols | Others
4714
 * [29]   Letters   ::=   'L' [ultmo]?
4715
 * [30]   Marks   ::=   'M' [nce]?
4716
 * [31]   Numbers   ::=   'N' [dlo]?
4717
 * [32]   Punctuation   ::=   'P' [cdseifo]?
4718
 * [33]   Separators   ::=   'Z' [slp]?
4719
 * [34]   Symbols   ::=   'S' [mcko]?
4720
 * [35]   Others   ::=   'C' [cfon]?
4721
 * [36]   IsBlock   ::=   'Is' [a-zA-Z0-9#x2D]+
4722
 */
4723
static void
4724
0
xmlFAParseCharProp(xmlRegParserCtxtPtr ctxt) {
4725
0
    int cur;
4726
0
    xmlRegAtomType type = (xmlRegAtomType) 0;
4727
0
    xmlChar *blockName = NULL;
4728
4729
0
    cur = CUR;
4730
0
    if (cur == 'L') {
4731
0
  NEXT;
4732
0
  cur = CUR;
4733
0
  if (cur == 'u') {
4734
0
      NEXT;
4735
0
      type = XML_REGEXP_LETTER_UPPERCASE;
4736
0
  } else if (cur == 'l') {
4737
0
      NEXT;
4738
0
      type = XML_REGEXP_LETTER_LOWERCASE;
4739
0
  } else if (cur == 't') {
4740
0
      NEXT;
4741
0
      type = XML_REGEXP_LETTER_TITLECASE;
4742
0
  } else if (cur == 'm') {
4743
0
      NEXT;
4744
0
      type = XML_REGEXP_LETTER_MODIFIER;
4745
0
  } else if (cur == 'o') {
4746
0
      NEXT;
4747
0
      type = XML_REGEXP_LETTER_OTHERS;
4748
0
  } else {
4749
0
      type = XML_REGEXP_LETTER;
4750
0
  }
4751
0
    } else if (cur == 'M') {
4752
0
  NEXT;
4753
0
  cur = CUR;
4754
0
  if (cur == 'n') {
4755
0
      NEXT;
4756
      /* nonspacing */
4757
0
      type = XML_REGEXP_MARK_NONSPACING;
4758
0
  } else if (cur == 'c') {
4759
0
      NEXT;
4760
      /* spacing combining */
4761
0
      type = XML_REGEXP_MARK_SPACECOMBINING;
4762
0
  } else if (cur == 'e') {
4763
0
      NEXT;
4764
      /* enclosing */
4765
0
      type = XML_REGEXP_MARK_ENCLOSING;
4766
0
  } else {
4767
      /* all marks */
4768
0
      type = XML_REGEXP_MARK;
4769
0
  }
4770
0
    } else if (cur == 'N') {
4771
0
  NEXT;
4772
0
  cur = CUR;
4773
0
  if (cur == 'd') {
4774
0
      NEXT;
4775
      /* digital */
4776
0
      type = XML_REGEXP_NUMBER_DECIMAL;
4777
0
  } else if (cur == 'l') {
4778
0
      NEXT;
4779
      /* letter */
4780
0
      type = XML_REGEXP_NUMBER_LETTER;
4781
0
  } else if (cur == 'o') {
4782
0
      NEXT;
4783
      /* other */
4784
0
      type = XML_REGEXP_NUMBER_OTHERS;
4785
0
  } else {
4786
      /* all numbers */
4787
0
      type = XML_REGEXP_NUMBER;
4788
0
  }
4789
0
    } else if (cur == 'P') {
4790
0
  NEXT;
4791
0
  cur = CUR;
4792
0
  if (cur == 'c') {
4793
0
      NEXT;
4794
      /* connector */
4795
0
      type = XML_REGEXP_PUNCT_CONNECTOR;
4796
0
  } else if (cur == 'd') {
4797
0
      NEXT;
4798
      /* dash */
4799
0
      type = XML_REGEXP_PUNCT_DASH;
4800
0
  } else if (cur == 's') {
4801
0
      NEXT;
4802
      /* open */
4803
0
      type = XML_REGEXP_PUNCT_OPEN;
4804
0
  } else if (cur == 'e') {
4805
0
      NEXT;
4806
      /* close */
4807
0
      type = XML_REGEXP_PUNCT_CLOSE;
4808
0
  } else if (cur == 'i') {
4809
0
      NEXT;
4810
      /* initial quote */
4811
0
      type = XML_REGEXP_PUNCT_INITQUOTE;
4812
0
  } else if (cur == 'f') {
4813
0
      NEXT;
4814
      /* final quote */
4815
0
      type = XML_REGEXP_PUNCT_FINQUOTE;
4816
0
  } else if (cur == 'o') {
4817
0
      NEXT;
4818
      /* other */
4819
0
      type = XML_REGEXP_PUNCT_OTHERS;
4820
0
  } else {
4821
      /* all punctuation */
4822
0
      type = XML_REGEXP_PUNCT;
4823
0
  }
4824
0
    } else if (cur == 'Z') {
4825
0
  NEXT;
4826
0
  cur = CUR;
4827
0
  if (cur == 's') {
4828
0
      NEXT;
4829
      /* space */
4830
0
      type = XML_REGEXP_SEPAR_SPACE;
4831
0
  } else if (cur == 'l') {
4832
0
      NEXT;
4833
      /* line */
4834
0
      type = XML_REGEXP_SEPAR_LINE;
4835
0
  } else if (cur == 'p') {
4836
0
      NEXT;
4837
      /* paragraph */
4838
0
      type = XML_REGEXP_SEPAR_PARA;
4839
0
  } else {
4840
      /* all separators */
4841
0
      type = XML_REGEXP_SEPAR;
4842
0
  }
4843
0
    } else if (cur == 'S') {
4844
0
  NEXT;
4845
0
  cur = CUR;
4846
0
  if (cur == 'm') {
4847
0
      NEXT;
4848
0
      type = XML_REGEXP_SYMBOL_MATH;
4849
      /* math */
4850
0
  } else if (cur == 'c') {
4851
0
      NEXT;
4852
0
      type = XML_REGEXP_SYMBOL_CURRENCY;
4853
      /* currency */
4854
0
  } else if (cur == 'k') {
4855
0
      NEXT;
4856
0
      type = XML_REGEXP_SYMBOL_MODIFIER;
4857
      /* modifiers */
4858
0
  } else if (cur == 'o') {
4859
0
      NEXT;
4860
0
      type = XML_REGEXP_SYMBOL_OTHERS;
4861
      /* other */
4862
0
  } else {
4863
      /* all symbols */
4864
0
      type = XML_REGEXP_SYMBOL;
4865
0
  }
4866
0
    } else if (cur == 'C') {
4867
0
  NEXT;
4868
0
  cur = CUR;
4869
0
  if (cur == 'c') {
4870
0
      NEXT;
4871
      /* control */
4872
0
      type = XML_REGEXP_OTHER_CONTROL;
4873
0
  } else if (cur == 'f') {
4874
0
      NEXT;
4875
      /* format */
4876
0
      type = XML_REGEXP_OTHER_FORMAT;
4877
0
  } else if (cur == 'o') {
4878
0
      NEXT;
4879
      /* private use */
4880
0
      type = XML_REGEXP_OTHER_PRIVATE;
4881
0
  } else if (cur == 'n') {
4882
0
      NEXT;
4883
      /* not assigned */
4884
0
      type = XML_REGEXP_OTHER_NA;
4885
0
  } else {
4886
      /* all others */
4887
0
      type = XML_REGEXP_OTHER;
4888
0
  }
4889
0
    } else if (cur == 'I') {
4890
0
  const xmlChar *start;
4891
0
  NEXT;
4892
0
  cur = CUR;
4893
0
  if (cur != 's') {
4894
0
      ERROR("IsXXXX expected");
4895
0
      return;
4896
0
  }
4897
0
  NEXT;
4898
0
  start = ctxt->cur;
4899
0
  cur = CUR;
4900
0
  if (((cur >= 'a') && (cur <= 'z')) ||
4901
0
      ((cur >= 'A') && (cur <= 'Z')) ||
4902
0
      ((cur >= '0') && (cur <= '9')) ||
4903
0
      (cur == 0x2D)) {
4904
0
      NEXT;
4905
0
      cur = CUR;
4906
0
      while (((cur >= 'a') && (cur <= 'z')) ||
4907
0
    ((cur >= 'A') && (cur <= 'Z')) ||
4908
0
    ((cur >= '0') && (cur <= '9')) ||
4909
0
    (cur == 0x2D)) {
4910
0
    NEXT;
4911
0
    cur = CUR;
4912
0
      }
4913
0
  }
4914
0
  type = XML_REGEXP_BLOCK_NAME;
4915
0
  blockName = xmlStrndup(start, ctxt->cur - start);
4916
0
    } else {
4917
0
  ERROR("Unknown char property");
4918
0
  return;
4919
0
    }
4920
0
    if (ctxt->atom == NULL) {
4921
0
  ctxt->atom = xmlRegNewAtom(ctxt, type);
4922
0
        if (ctxt->atom == NULL) {
4923
0
            xmlFree(blockName);
4924
0
            return;
4925
0
        }
4926
0
  ctxt->atom->valuep = blockName;
4927
0
    } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
4928
0
        if (xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4929
0
                               type, 0, 0, blockName) == NULL) {
4930
0
            xmlFree(blockName);
4931
0
        }
4932
0
    }
4933
0
}
4934
4935
static int parse_escaped_codeunit(xmlRegParserCtxtPtr ctxt)
4936
0
{
4937
0
    int val = 0, i, cur;
4938
0
    for (i = 0; i < 4; i++) {
4939
0
  NEXT;
4940
0
  val *= 16;
4941
0
  cur = CUR;
4942
0
  if (cur >= '0' && cur <= '9') {
4943
0
      val += cur - '0';
4944
0
  } else if (cur >= 'A' && cur <= 'F') {
4945
0
      val += cur - 'A' + 10;
4946
0
  } else if (cur >= 'a' && cur <= 'f') {
4947
0
      val += cur - 'a' + 10;
4948
0
  } else {
4949
0
      ERROR("Expecting hex digit");
4950
0
      return -1;
4951
0
  }
4952
0
    }
4953
0
    return val;
4954
0
}
4955
4956
static int parse_escaped_codepoint(xmlRegParserCtxtPtr ctxt)
4957
0
{
4958
0
    int val = parse_escaped_codeunit(ctxt);
4959
0
    if (0xD800 <= val && val <= 0xDBFF) {
4960
0
  NEXT;
4961
0
  if (CUR == '\\') {
4962
0
      NEXT;
4963
0
      if (CUR == 'u') {
4964
0
    int low = parse_escaped_codeunit(ctxt);
4965
0
    if (0xDC00 <= low && low <= 0xDFFF) {
4966
0
        return (val - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000;
4967
0
    }
4968
0
      }
4969
0
  }
4970
0
  ERROR("Invalid low surrogate pair code unit");
4971
0
  val = -1;
4972
0
    }
4973
0
    return val;
4974
0
}
4975
4976
/**
4977
 * xmlFAParseCharClassEsc:
4978
 * @ctxt:  a regexp parser context
4979
 *
4980
 * [23] charClassEsc ::= ( SingleCharEsc | MultiCharEsc | catEsc | complEsc )
4981
 * [24] SingleCharEsc ::= '\' [nrt\|.?*+(){}#x2D#x5B#x5D#x5E]
4982
 * [25] catEsc   ::=   '\p{' charProp '}'
4983
 * [26] complEsc ::=   '\P{' charProp '}'
4984
 * [37] MultiCharEsc ::= '.' | ('\' [sSiIcCdDwW])
4985
 */
4986
static void
4987
0
xmlFAParseCharClassEsc(xmlRegParserCtxtPtr ctxt) {
4988
0
    int cur;
4989
4990
0
    if (CUR == '.') {
4991
0
  if (ctxt->atom == NULL) {
4992
0
      ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_ANYCHAR);
4993
0
  } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
4994
0
      xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
4995
0
             XML_REGEXP_ANYCHAR, 0, 0, NULL);
4996
0
  }
4997
0
  NEXT;
4998
0
  return;
4999
0
    }
5000
0
    if (CUR != '\\') {
5001
0
  ERROR("Escaped sequence: expecting \\");
5002
0
  return;
5003
0
    }
5004
0
    NEXT;
5005
0
    cur = CUR;
5006
0
    if (cur == 'p') {
5007
0
  NEXT;
5008
0
  if (CUR != '{') {
5009
0
      ERROR("Expecting '{'");
5010
0
      return;
5011
0
  }
5012
0
  NEXT;
5013
0
  xmlFAParseCharProp(ctxt);
5014
0
  if (CUR != '}') {
5015
0
      ERROR("Expecting '}'");
5016
0
      return;
5017
0
  }
5018
0
  NEXT;
5019
0
    } else if (cur == 'P') {
5020
0
  NEXT;
5021
0
  if (CUR != '{') {
5022
0
      ERROR("Expecting '{'");
5023
0
      return;
5024
0
  }
5025
0
  NEXT;
5026
0
  xmlFAParseCharProp(ctxt);
5027
0
        if (ctxt->atom != NULL)
5028
0
      ctxt->atom->neg = 1;
5029
0
  if (CUR != '}') {
5030
0
      ERROR("Expecting '}'");
5031
0
      return;
5032
0
  }
5033
0
  NEXT;
5034
0
    } else if ((cur == 'n') || (cur == 'r') || (cur == 't') || (cur == '\\') ||
5035
0
  (cur == '|') || (cur == '.') || (cur == '?') || (cur == '*') ||
5036
0
  (cur == '+') || (cur == '(') || (cur == ')') || (cur == '{') ||
5037
0
  (cur == '}') || (cur == 0x2D) || (cur == 0x5B) || (cur == 0x5D) ||
5038
0
  (cur == 0x5E) ||
5039
5040
  /* Non-standard escape sequences:
5041
   *                  Java 1.8|.NET Core 3.1|MSXML 6 */
5042
0
  (cur == '!') ||     /*   +  |     +       |    +   */
5043
0
  (cur == '"') ||     /*   +  |     +       |    +   */
5044
0
  (cur == '#') ||     /*   +  |     +       |    +   */
5045
0
  (cur == '$') ||     /*   +  |     +       |    +   */
5046
0
  (cur == '%') ||     /*   +  |     +       |    +   */
5047
0
  (cur == ',') ||     /*   +  |     +       |    +   */
5048
0
  (cur == '/') ||     /*   +  |     +       |    +   */
5049
0
  (cur == ':') ||     /*   +  |     +       |    +   */
5050
0
  (cur == ';') ||     /*   +  |     +       |    +   */
5051
0
  (cur == '=') ||     /*   +  |     +       |    +   */
5052
0
  (cur == '>') ||     /*      |     +       |    +   */
5053
0
  (cur == '@') ||     /*   +  |     +       |    +   */
5054
0
  (cur == '`') ||     /*   +  |     +       |    +   */
5055
0
  (cur == '~') ||     /*   +  |     +       |    +   */
5056
0
  (cur == 'u')) {     /*      |     +       |    +   */
5057
0
  if (ctxt->atom == NULL) {
5058
0
      ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_CHARVAL);
5059
0
      if (ctxt->atom != NULL) {
5060
0
          switch (cur) {
5061
0
        case 'n':
5062
0
            ctxt->atom->codepoint = '\n';
5063
0
      break;
5064
0
        case 'r':
5065
0
            ctxt->atom->codepoint = '\r';
5066
0
      break;
5067
0
        case 't':
5068
0
            ctxt->atom->codepoint = '\t';
5069
0
      break;
5070
0
        case 'u':
5071
0
      cur = parse_escaped_codepoint(ctxt);
5072
0
      if (cur < 0) {
5073
0
          return;
5074
0
      }
5075
0
      ctxt->atom->codepoint = cur;
5076
0
      break;
5077
0
        default:
5078
0
      ctxt->atom->codepoint = cur;
5079
0
    }
5080
0
      }
5081
0
  } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
5082
0
            switch (cur) {
5083
0
                case 'n':
5084
0
                    cur = '\n';
5085
0
                    break;
5086
0
                case 'r':
5087
0
                    cur = '\r';
5088
0
                    break;
5089
0
                case 't':
5090
0
                    cur = '\t';
5091
0
                    break;
5092
0
            }
5093
0
      xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
5094
0
             XML_REGEXP_CHARVAL, cur, cur, NULL);
5095
0
  }
5096
0
  NEXT;
5097
0
    } else if ((cur == 's') || (cur == 'S') || (cur == 'i') || (cur == 'I') ||
5098
0
  (cur == 'c') || (cur == 'C') || (cur == 'd') || (cur == 'D') ||
5099
0
  (cur == 'w') || (cur == 'W')) {
5100
0
  xmlRegAtomType type = XML_REGEXP_ANYSPACE;
5101
5102
0
  switch (cur) {
5103
0
      case 's':
5104
0
    type = XML_REGEXP_ANYSPACE;
5105
0
    break;
5106
0
      case 'S':
5107
0
    type = XML_REGEXP_NOTSPACE;
5108
0
    break;
5109
0
      case 'i':
5110
0
    type = XML_REGEXP_INITNAME;
5111
0
    break;
5112
0
      case 'I':
5113
0
    type = XML_REGEXP_NOTINITNAME;
5114
0
    break;
5115
0
      case 'c':
5116
0
    type = XML_REGEXP_NAMECHAR;
5117
0
    break;
5118
0
      case 'C':
5119
0
    type = XML_REGEXP_NOTNAMECHAR;
5120
0
    break;
5121
0
      case 'd':
5122
0
    type = XML_REGEXP_DECIMAL;
5123
0
    break;
5124
0
      case 'D':
5125
0
    type = XML_REGEXP_NOTDECIMAL;
5126
0
    break;
5127
0
      case 'w':
5128
0
    type = XML_REGEXP_REALCHAR;
5129
0
    break;
5130
0
      case 'W':
5131
0
    type = XML_REGEXP_NOTREALCHAR;
5132
0
    break;
5133
0
  }
5134
0
  NEXT;
5135
0
  if (ctxt->atom == NULL) {
5136
0
      ctxt->atom = xmlRegNewAtom(ctxt, type);
5137
0
  } else if (ctxt->atom->type == XML_REGEXP_RANGES) {
5138
0
      xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
5139
0
             type, 0, 0, NULL);
5140
0
  }
5141
0
    } else {
5142
0
  ERROR("Wrong escape sequence, misuse of character '\\'");
5143
0
    }
5144
0
}
5145
5146
/**
5147
 * xmlFAParseCharRange:
5148
 * @ctxt:  a regexp parser context
5149
 *
5150
 * [17]   charRange   ::=     seRange | XmlCharRef | XmlCharIncDash
5151
 * [18]   seRange   ::=   charOrEsc '-' charOrEsc
5152
 * [20]   charOrEsc   ::=   XmlChar | SingleCharEsc
5153
 * [21]   XmlChar   ::=   [^\#x2D#x5B#x5D]
5154
 * [22]   XmlCharIncDash   ::=   [^\#x5B#x5D]
5155
 */
5156
static void
5157
0
xmlFAParseCharRange(xmlRegParserCtxtPtr ctxt) {
5158
0
    int cur, len;
5159
0
    int start = -1;
5160
0
    int end = -1;
5161
5162
0
    if (CUR == '\0') {
5163
0
        ERROR("Expecting ']'");
5164
0
  return;
5165
0
    }
5166
5167
0
    cur = CUR;
5168
0
    if (cur == '\\') {
5169
0
  NEXT;
5170
0
  cur = CUR;
5171
0
  switch (cur) {
5172
0
      case 'n': start = 0xA; break;
5173
0
      case 'r': start = 0xD; break;
5174
0
      case 't': start = 0x9; break;
5175
0
      case '\\': case '|': case '.': case '-': case '^': case '?':
5176
0
      case '*': case '+': case '{': case '}': case '(': case ')':
5177
0
      case '[': case ']':
5178
0
    start = cur; break;
5179
0
      default:
5180
0
    ERROR("Invalid escape value");
5181
0
    return;
5182
0
  }
5183
0
  end = start;
5184
0
        len = 1;
5185
0
    } else if ((cur != 0x5B) && (cur != 0x5D)) {
5186
0
        end = start = CUR_SCHAR(ctxt->cur, len);
5187
0
    } else {
5188
0
  ERROR("Expecting a char range");
5189
0
  return;
5190
0
    }
5191
    /*
5192
     * Since we are "inside" a range, we can assume ctxt->cur is past
5193
     * the start of ctxt->string, and PREV should be safe
5194
     */
5195
0
    if ((start == '-') && (NXT(1) != ']') && (PREV != '[') && (PREV != '^')) {
5196
0
  NEXTL(len);
5197
0
  return;
5198
0
    }
5199
0
    NEXTL(len);
5200
0
    cur = CUR;
5201
0
    if ((cur != '-') || (NXT(1) == '[') || (NXT(1) == ']')) {
5202
0
        xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
5203
0
                  XML_REGEXP_CHARVAL, start, end, NULL);
5204
0
  return;
5205
0
    }
5206
0
    NEXT;
5207
0
    cur = CUR;
5208
0
    if (cur == '\\') {
5209
0
  NEXT;
5210
0
  cur = CUR;
5211
0
  switch (cur) {
5212
0
      case 'n': end = 0xA; break;
5213
0
      case 'r': end = 0xD; break;
5214
0
      case 't': end = 0x9; break;
5215
0
      case '\\': case '|': case '.': case '-': case '^': case '?':
5216
0
      case '*': case '+': case '{': case '}': case '(': case ')':
5217
0
      case '[': case ']':
5218
0
    end = cur; break;
5219
0
      default:
5220
0
    ERROR("Invalid escape value");
5221
0
    return;
5222
0
  }
5223
0
        len = 1;
5224
0
    } else if ((cur != '\0') && (cur != 0x5B) && (cur != 0x5D)) {
5225
0
        end = CUR_SCHAR(ctxt->cur, len);
5226
0
    } else {
5227
0
  ERROR("Expecting the end of a char range");
5228
0
  return;
5229
0
    }
5230
5231
    /* TODO check that the values are acceptable character ranges for XML */
5232
0
    if (end < start) {
5233
0
  ERROR("End of range is before start of range");
5234
0
    } else {
5235
0
        NEXTL(len);
5236
0
        xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
5237
0
               XML_REGEXP_CHARVAL, start, end, NULL);
5238
0
    }
5239
0
    return;
5240
0
}
5241
5242
/**
5243
 * xmlFAParsePosCharGroup:
5244
 * @ctxt:  a regexp parser context
5245
 *
5246
 * [14]   posCharGroup ::= ( charRange | charClassEsc  )+
5247
 */
5248
static void
5249
0
xmlFAParsePosCharGroup(xmlRegParserCtxtPtr ctxt) {
5250
0
    do {
5251
0
  if (CUR == '\\') {
5252
0
      xmlFAParseCharClassEsc(ctxt);
5253
0
  } else {
5254
0
      xmlFAParseCharRange(ctxt);
5255
0
  }
5256
0
    } while ((CUR != ']') && (CUR != '-') &&
5257
0
             (CUR != 0) && (ctxt->error == 0));
5258
0
}
5259
5260
/**
5261
 * xmlFAParseCharGroup:
5262
 * @ctxt:  a regexp parser context
5263
 *
5264
 * [13]   charGroup    ::= posCharGroup | negCharGroup | charClassSub
5265
 * [15]   negCharGroup ::= '^' posCharGroup
5266
 * [16]   charClassSub ::= ( posCharGroup | negCharGroup ) '-' charClassExpr
5267
 * [12]   charClassExpr ::= '[' charGroup ']'
5268
 */
5269
static void
5270
0
xmlFAParseCharGroup(xmlRegParserCtxtPtr ctxt) {
5271
0
    int neg = ctxt->neg;
5272
5273
0
    if (CUR == '^') {
5274
0
  NEXT;
5275
0
  ctxt->neg = !ctxt->neg;
5276
0
  xmlFAParsePosCharGroup(ctxt);
5277
0
  ctxt->neg = neg;
5278
0
    }
5279
0
    while ((CUR != ']') && (ctxt->error == 0)) {
5280
0
  if ((CUR == '-') && (NXT(1) == '[')) {
5281
0
      NEXT; /* eat the '-' */
5282
0
      NEXT; /* eat the '[' */
5283
0
      ctxt->neg = 2;
5284
0
      xmlFAParseCharGroup(ctxt);
5285
0
      ctxt->neg = neg;
5286
0
      if (CUR == ']') {
5287
0
    NEXT;
5288
0
      } else {
5289
0
    ERROR("charClassExpr: ']' expected");
5290
0
      }
5291
0
      break;
5292
0
  } else {
5293
0
      xmlFAParsePosCharGroup(ctxt);
5294
0
  }
5295
0
    }
5296
0
}
5297
5298
/**
5299
 * xmlFAParseCharClass:
5300
 * @ctxt:  a regexp parser context
5301
 *
5302
 * [11]   charClass   ::=     charClassEsc | charClassExpr
5303
 * [12]   charClassExpr   ::=   '[' charGroup ']'
5304
 */
5305
static void
5306
0
xmlFAParseCharClass(xmlRegParserCtxtPtr ctxt) {
5307
0
    if (CUR == '[') {
5308
0
  NEXT;
5309
0
  ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_RANGES);
5310
0
  if (ctxt->atom == NULL)
5311
0
      return;
5312
0
  xmlFAParseCharGroup(ctxt);
5313
0
  if (CUR == ']') {
5314
0
      NEXT;
5315
0
  } else {
5316
0
      ERROR("xmlFAParseCharClass: ']' expected");
5317
0
  }
5318
0
    } else {
5319
0
  xmlFAParseCharClassEsc(ctxt);
5320
0
    }
5321
0
}
5322
5323
/**
5324
 * xmlFAParseQuantExact:
5325
 * @ctxt:  a regexp parser context
5326
 *
5327
 * [8]   QuantExact   ::=   [0-9]+
5328
 *
5329
 * Returns 0 if success or -1 in case of error
5330
 */
5331
static int
5332
0
xmlFAParseQuantExact(xmlRegParserCtxtPtr ctxt) {
5333
0
    int ret = 0;
5334
0
    int ok = 0;
5335
0
    int overflow = 0;
5336
5337
0
    while ((CUR >= '0') && (CUR <= '9')) {
5338
0
        if (ret > INT_MAX / 10) {
5339
0
            overflow = 1;
5340
0
        } else {
5341
0
            int digit = CUR - '0';
5342
5343
0
            ret *= 10;
5344
0
            if (ret > INT_MAX - digit)
5345
0
                overflow = 1;
5346
0
            else
5347
0
                ret += digit;
5348
0
        }
5349
0
  ok = 1;
5350
0
  NEXT;
5351
0
    }
5352
0
    if ((ok != 1) || (overflow == 1)) {
5353
0
  return(-1);
5354
0
    }
5355
0
    return(ret);
5356
0
}
5357
5358
/**
5359
 * xmlFAParseQuantifier:
5360
 * @ctxt:  a regexp parser context
5361
 *
5362
 * [4]   quantifier   ::=   [?*+] | ( '{' quantity '}' )
5363
 * [5]   quantity   ::=   quantRange | quantMin | QuantExact
5364
 * [6]   quantRange   ::=   QuantExact ',' QuantExact
5365
 * [7]   quantMin   ::=   QuantExact ','
5366
 * [8]   QuantExact   ::=   [0-9]+
5367
 */
5368
static int
5369
0
xmlFAParseQuantifier(xmlRegParserCtxtPtr ctxt) {
5370
0
    int cur;
5371
5372
0
    cur = CUR;
5373
0
    if ((cur == '?') || (cur == '*') || (cur == '+')) {
5374
0
  if (ctxt->atom != NULL) {
5375
0
      if (cur == '?')
5376
0
    ctxt->atom->quant = XML_REGEXP_QUANT_OPT;
5377
0
      else if (cur == '*')
5378
0
    ctxt->atom->quant = XML_REGEXP_QUANT_MULT;
5379
0
      else if (cur == '+')
5380
0
    ctxt->atom->quant = XML_REGEXP_QUANT_PLUS;
5381
0
  }
5382
0
  NEXT;
5383
0
  return(1);
5384
0
    }
5385
0
    if (cur == '{') {
5386
0
  int min = 0, max = 0;
5387
5388
0
  NEXT;
5389
0
  cur = xmlFAParseQuantExact(ctxt);
5390
0
  if (cur >= 0)
5391
0
      min = cur;
5392
0
        else {
5393
0
            ERROR("Improper quantifier");
5394
0
        }
5395
0
  if (CUR == ',') {
5396
0
      NEXT;
5397
0
      if (CUR == '}')
5398
0
          max = INT_MAX;
5399
0
      else {
5400
0
          cur = xmlFAParseQuantExact(ctxt);
5401
0
          if (cur >= 0)
5402
0
        max = cur;
5403
0
    else {
5404
0
        ERROR("Improper quantifier");
5405
0
    }
5406
0
      }
5407
0
  }
5408
0
  if (CUR == '}') {
5409
0
      NEXT;
5410
0
  } else {
5411
0
      ERROR("Unterminated quantifier");
5412
0
  }
5413
0
  if (max == 0)
5414
0
      max = min;
5415
0
  if (ctxt->atom != NULL) {
5416
0
      ctxt->atom->quant = XML_REGEXP_QUANT_RANGE;
5417
0
      ctxt->atom->min = min;
5418
0
      ctxt->atom->max = max;
5419
0
  }
5420
0
  return(1);
5421
0
    }
5422
0
    return(0);
5423
0
}
5424
5425
/**
5426
 * xmlFAParseAtom:
5427
 * @ctxt:  a regexp parser context
5428
 *
5429
 * [9]   atom   ::=   Char | charClass | ( '(' regExp ')' )
5430
 */
5431
static int
5432
0
xmlFAParseAtom(xmlRegParserCtxtPtr ctxt) {
5433
0
    int codepoint, len;
5434
5435
0
    codepoint = xmlFAIsChar(ctxt);
5436
0
    if (codepoint > 0) {
5437
0
  ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_CHARVAL);
5438
0
  if (ctxt->atom == NULL)
5439
0
      return(-1);
5440
0
  codepoint = CUR_SCHAR(ctxt->cur, len);
5441
0
  ctxt->atom->codepoint = codepoint;
5442
0
  NEXTL(len);
5443
0
  return(1);
5444
0
    } else if (CUR == '|') {
5445
0
  return(0);
5446
0
    } else if (CUR == 0) {
5447
0
  return(0);
5448
0
    } else if (CUR == ')') {
5449
0
  return(0);
5450
0
    } else if (CUR == '(') {
5451
0
  xmlRegStatePtr start, oldend, start0;
5452
5453
0
  NEXT;
5454
0
        if (ctxt->depth >= 50) {
5455
0
      ERROR("xmlFAParseAtom: maximum nesting depth exceeded");
5456
0
            return(-1);
5457
0
        }
5458
  /*
5459
   * this extra Epsilon transition is needed if we count with 0 allowed
5460
   * unfortunately this can't be known at that point
5461
   */
5462
0
  xmlFAGenerateEpsilonTransition(ctxt, ctxt->state, NULL);
5463
0
  start0 = ctxt->state;
5464
0
  xmlFAGenerateEpsilonTransition(ctxt, ctxt->state, NULL);
5465
0
  start = ctxt->state;
5466
0
  oldend = ctxt->end;
5467
0
  ctxt->end = NULL;
5468
0
  ctxt->atom = NULL;
5469
0
        ctxt->depth++;
5470
0
  xmlFAParseRegExp(ctxt, 0);
5471
0
        ctxt->depth--;
5472
0
  if (CUR == ')') {
5473
0
      NEXT;
5474
0
  } else {
5475
0
      ERROR("xmlFAParseAtom: expecting ')'");
5476
0
  }
5477
0
  ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_SUBREG);
5478
0
  if (ctxt->atom == NULL)
5479
0
      return(-1);
5480
0
  ctxt->atom->start = start;
5481
0
  ctxt->atom->start0 = start0;
5482
0
  ctxt->atom->stop = ctxt->state;
5483
0
  ctxt->end = oldend;
5484
0
  return(1);
5485
0
    } else if ((CUR == '[') || (CUR == '\\') || (CUR == '.')) {
5486
0
  xmlFAParseCharClass(ctxt);
5487
0
  return(1);
5488
0
    }
5489
0
    return(0);
5490
0
}
5491
5492
/**
5493
 * xmlFAParsePiece:
5494
 * @ctxt:  a regexp parser context
5495
 *
5496
 * [3]   piece   ::=   atom quantifier?
5497
 */
5498
static int
5499
0
xmlFAParsePiece(xmlRegParserCtxtPtr ctxt) {
5500
0
    int ret;
5501
5502
0
    ctxt->atom = NULL;
5503
0
    ret = xmlFAParseAtom(ctxt);
5504
0
    if (ret == 0)
5505
0
  return(0);
5506
0
    if (ctxt->atom == NULL) {
5507
0
  ERROR("internal: no atom generated");
5508
0
    }
5509
0
    xmlFAParseQuantifier(ctxt);
5510
0
    return(1);
5511
0
}
5512
5513
/**
5514
 * xmlFAParseBranch:
5515
 * @ctxt:  a regexp parser context
5516
 * @to: optional target to the end of the branch
5517
 *
5518
 * @to is used to optimize by removing duplicate path in automata
5519
 * in expressions like (a|b)(c|d)
5520
 *
5521
 * [2]   branch   ::=   piece*
5522
 */
5523
static int
5524
0
xmlFAParseBranch(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr to) {
5525
0
    xmlRegStatePtr previous;
5526
0
    int ret;
5527
5528
0
    previous = ctxt->state;
5529
0
    ret = xmlFAParsePiece(ctxt);
5530
0
    if (ret == 0) {
5531
        /* Empty branch */
5532
0
  xmlFAGenerateEpsilonTransition(ctxt, previous, to);
5533
0
    } else {
5534
0
  if (xmlFAGenerateTransitions(ctxt, previous,
5535
0
          (CUR=='|' || CUR==')' || CUR==0) ? to : NULL,
5536
0
                ctxt->atom) < 0) {
5537
0
            xmlRegFreeAtom(ctxt->atom);
5538
0
            ctxt->atom = NULL;
5539
0
      return(-1);
5540
0
        }
5541
0
  previous = ctxt->state;
5542
0
  ctxt->atom = NULL;
5543
0
    }
5544
0
    while ((ret != 0) && (ctxt->error == 0)) {
5545
0
  ret = xmlFAParsePiece(ctxt);
5546
0
  if (ret != 0) {
5547
0
      if (xmlFAGenerateTransitions(ctxt, previous,
5548
0
              (CUR=='|' || CUR==')' || CUR==0) ? to : NULL,
5549
0
                    ctxt->atom) < 0) {
5550
0
                xmlRegFreeAtom(ctxt->atom);
5551
0
                ctxt->atom = NULL;
5552
0
                return(-1);
5553
0
            }
5554
0
      previous = ctxt->state;
5555
0
      ctxt->atom = NULL;
5556
0
  }
5557
0
    }
5558
0
    return(0);
5559
0
}
5560
5561
/**
5562
 * xmlFAParseRegExp:
5563
 * @ctxt:  a regexp parser context
5564
 * @top:  is this the top-level expression ?
5565
 *
5566
 * [1]   regExp   ::=     branch  ( '|' branch )*
5567
 */
5568
static void
5569
0
xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top) {
5570
0
    xmlRegStatePtr start, end;
5571
5572
    /* if not top start should have been generated by an epsilon trans */
5573
0
    start = ctxt->state;
5574
0
    ctxt->end = NULL;
5575
0
    xmlFAParseBranch(ctxt, NULL);
5576
0
    if (top) {
5577
#ifdef DEBUG_REGEXP_GRAPH
5578
  printf("State %d is final\n", ctxt->state->no);
5579
#endif
5580
0
  ctxt->state->type = XML_REGEXP_FINAL_STATE;
5581
0
    }
5582
0
    if (CUR != '|') {
5583
0
  ctxt->end = ctxt->state;
5584
0
  return;
5585
0
    }
5586
0
    end = ctxt->state;
5587
0
    while ((CUR == '|') && (ctxt->error == 0)) {
5588
0
  NEXT;
5589
0
  ctxt->state = start;
5590
0
  ctxt->end = NULL;
5591
0
  xmlFAParseBranch(ctxt, end);
5592
0
    }
5593
0
    if (!top) {
5594
0
  ctxt->state = end;
5595
0
  ctxt->end = end;
5596
0
    }
5597
0
}
5598
5599
/************************************************************************
5600
 *                  *
5601
 *      The basic API         *
5602
 *                  *
5603
 ************************************************************************/
5604
5605
/**
5606
 * xmlRegexpPrint:
5607
 * @output: the file for the output debug
5608
 * @regexp: the compiled regexp
5609
 *
5610
 * Print the content of the compiled regular expression
5611
 */
5612
void
5613
0
xmlRegexpPrint(FILE *output, xmlRegexpPtr regexp) {
5614
0
    int i;
5615
5616
0
    if (output == NULL)
5617
0
        return;
5618
0
    fprintf(output, " regexp: ");
5619
0
    if (regexp == NULL) {
5620
0
  fprintf(output, "NULL\n");
5621
0
  return;
5622
0
    }
5623
0
    fprintf(output, "'%s' ", regexp->string);
5624
0
    fprintf(output, "\n");
5625
0
    fprintf(output, "%d atoms:\n", regexp->nbAtoms);
5626
0
    for (i = 0;i < regexp->nbAtoms; i++) {
5627
0
  fprintf(output, " %02d ", i);
5628
0
  xmlRegPrintAtom(output, regexp->atoms[i]);
5629
0
    }
5630
0
    fprintf(output, "%d states:", regexp->nbStates);
5631
0
    fprintf(output, "\n");
5632
0
    for (i = 0;i < regexp->nbStates; i++) {
5633
0
  xmlRegPrintState(output, regexp->states[i]);
5634
0
    }
5635
0
    fprintf(output, "%d counters:\n", regexp->nbCounters);
5636
0
    for (i = 0;i < regexp->nbCounters; i++) {
5637
0
  fprintf(output, " %d: min %d max %d\n", i, regexp->counters[i].min,
5638
0
                                    regexp->counters[i].max);
5639
0
    }
5640
0
}
5641
5642
/**
5643
 * xmlRegexpCompile:
5644
 * @regexp:  a regular expression string
5645
 *
5646
 * Parses a regular expression conforming to XML Schemas Part 2 Datatype
5647
 * Appendix F and builds an automata suitable for testing strings against
5648
 * that regular expression
5649
 *
5650
 * Returns the compiled expression or NULL in case of error
5651
 */
5652
xmlRegexpPtr
5653
0
xmlRegexpCompile(const xmlChar *regexp) {
5654
0
    xmlRegexpPtr ret = NULL;
5655
0
    xmlRegParserCtxtPtr ctxt;
5656
5657
0
    ctxt = xmlRegNewParserCtxt(regexp);
5658
0
    if (ctxt == NULL)
5659
0
  return(NULL);
5660
5661
    /* initialize the parser */
5662
0
    ctxt->state = xmlRegStatePush(ctxt);
5663
0
    if (ctxt->state == NULL)
5664
0
        goto error;
5665
0
    ctxt->start = ctxt->state;
5666
0
    ctxt->end = NULL;
5667
5668
    /* parse the expression building an automata */
5669
0
    xmlFAParseRegExp(ctxt, 1);
5670
0
    if (CUR != 0) {
5671
0
  ERROR("xmlFAParseRegExp: extra characters");
5672
0
    }
5673
0
    if (ctxt->error != 0)
5674
0
        goto error;
5675
0
    ctxt->end = ctxt->state;
5676
0
    ctxt->start->type = XML_REGEXP_START_STATE;
5677
0
    ctxt->end->type = XML_REGEXP_FINAL_STATE;
5678
5679
    /* remove the Epsilon except for counted transitions */
5680
0
    xmlFAEliminateEpsilonTransitions(ctxt);
5681
5682
5683
0
    if (ctxt->error != 0)
5684
0
        goto error;
5685
0
    ret = xmlRegEpxFromParse(ctxt);
5686
5687
0
error:
5688
0
    xmlRegFreeParserCtxt(ctxt);
5689
0
    return(ret);
5690
0
}
5691
5692
/**
5693
 * xmlRegexpExec:
5694
 * @comp:  the compiled regular expression
5695
 * @content:  the value to check against the regular expression
5696
 *
5697
 * Check if the regular expression generates the value
5698
 *
5699
 * Returns 1 if it matches, 0 if not and a negative value in case of error
5700
 */
5701
int
5702
0
xmlRegexpExec(xmlRegexpPtr comp, const xmlChar *content) {
5703
0
    if ((comp == NULL) || (content == NULL))
5704
0
  return(-1);
5705
0
    return(xmlFARegExec(comp, content));
5706
0
}
5707
5708
/**
5709
 * xmlRegexpIsDeterminist:
5710
 * @comp:  the compiled regular expression
5711
 *
5712
 * Check if the regular expression is determinist
5713
 *
5714
 * Returns 1 if it yes, 0 if not and a negative value in case of error
5715
 */
5716
int
5717
0
xmlRegexpIsDeterminist(xmlRegexpPtr comp) {
5718
0
    xmlAutomataPtr am;
5719
0
    int ret;
5720
5721
0
    if (comp == NULL)
5722
0
  return(-1);
5723
0
    if (comp->determinist != -1)
5724
0
  return(comp->determinist);
5725
5726
0
    am = xmlNewAutomata();
5727
0
    if (am == NULL)
5728
0
        return(-1);
5729
0
    if (am->states != NULL) {
5730
0
  int i;
5731
5732
0
  for (i = 0;i < am->nbStates;i++)
5733
0
      xmlRegFreeState(am->states[i]);
5734
0
  xmlFree(am->states);
5735
0
    }
5736
0
    am->nbAtoms = comp->nbAtoms;
5737
0
    am->atoms = comp->atoms;
5738
0
    am->nbStates = comp->nbStates;
5739
0
    am->states = comp->states;
5740
0
    am->determinist = -1;
5741
0
    am->flags = comp->flags;
5742
0
    ret = xmlFAComputesDeterminism(am);
5743
0
    am->atoms = NULL;
5744
0
    am->states = NULL;
5745
0
    xmlFreeAutomata(am);
5746
0
    comp->determinist = ret;
5747
0
    return(ret);
5748
0
}
5749
5750
/**
5751
 * xmlRegFreeRegexp:
5752
 * @regexp:  the regexp
5753
 *
5754
 * Free a regexp
5755
 */
5756
void
5757
0
xmlRegFreeRegexp(xmlRegexpPtr regexp) {
5758
0
    int i;
5759
0
    if (regexp == NULL)
5760
0
  return;
5761
5762
0
    if (regexp->string != NULL)
5763
0
  xmlFree(regexp->string);
5764
0
    if (regexp->states != NULL) {
5765
0
  for (i = 0;i < regexp->nbStates;i++)
5766
0
      xmlRegFreeState(regexp->states[i]);
5767
0
  xmlFree(regexp->states);
5768
0
    }
5769
0
    if (regexp->atoms != NULL) {
5770
0
  for (i = 0;i < regexp->nbAtoms;i++)
5771
0
      xmlRegFreeAtom(regexp->atoms[i]);
5772
0
  xmlFree(regexp->atoms);
5773
0
    }
5774
0
    if (regexp->counters != NULL)
5775
0
  xmlFree(regexp->counters);
5776
0
    if (regexp->compact != NULL)
5777
0
  xmlFree(regexp->compact);
5778
0
    if (regexp->transdata != NULL)
5779
0
  xmlFree(regexp->transdata);
5780
0
    if (regexp->stringMap != NULL) {
5781
0
  for (i = 0; i < regexp->nbstrings;i++)
5782
0
      xmlFree(regexp->stringMap[i]);
5783
0
  xmlFree(regexp->stringMap);
5784
0
    }
5785
5786
0
    xmlFree(regexp);
5787
0
}
5788
5789
#ifdef LIBXML_AUTOMATA_ENABLED
5790
/************************************************************************
5791
 *                  *
5792
 *      The Automata interface        *
5793
 *                  *
5794
 ************************************************************************/
5795
5796
/**
5797
 * xmlNewAutomata:
5798
 *
5799
 * Create a new automata
5800
 *
5801
 * Returns the new object or NULL in case of failure
5802
 */
5803
xmlAutomataPtr
5804
0
xmlNewAutomata(void) {
5805
0
    xmlAutomataPtr ctxt;
5806
5807
0
    ctxt = xmlRegNewParserCtxt(NULL);
5808
0
    if (ctxt == NULL)
5809
0
  return(NULL);
5810
5811
    /* initialize the parser */
5812
0
    ctxt->state = xmlRegStatePush(ctxt);
5813
0
    if (ctxt->state == NULL) {
5814
0
  xmlFreeAutomata(ctxt);
5815
0
  return(NULL);
5816
0
    }
5817
0
    ctxt->start = ctxt->state;
5818
0
    ctxt->end = NULL;
5819
5820
0
    ctxt->start->type = XML_REGEXP_START_STATE;
5821
0
    ctxt->flags = 0;
5822
5823
0
    return(ctxt);
5824
0
}
5825
5826
/**
5827
 * xmlFreeAutomata:
5828
 * @am: an automata
5829
 *
5830
 * Free an automata
5831
 */
5832
void
5833
0
xmlFreeAutomata(xmlAutomataPtr am) {
5834
0
    if (am == NULL)
5835
0
  return;
5836
0
    xmlRegFreeParserCtxt(am);
5837
0
}
5838
5839
/**
5840
 * xmlAutomataSetFlags:
5841
 * @am: an automata
5842
 * @flags:  a set of internal flags
5843
 *
5844
 * Set some flags on the automata
5845
 */
5846
void
5847
0
xmlAutomataSetFlags(xmlAutomataPtr am, int flags) {
5848
0
    if (am == NULL)
5849
0
  return;
5850
0
    am->flags |= flags;
5851
0
}
5852
5853
/**
5854
 * xmlAutomataGetInitState:
5855
 * @am: an automata
5856
 *
5857
 * Initial state lookup
5858
 *
5859
 * Returns the initial state of the automata
5860
 */
5861
xmlAutomataStatePtr
5862
0
xmlAutomataGetInitState(xmlAutomataPtr am) {
5863
0
    if (am == NULL)
5864
0
  return(NULL);
5865
0
    return(am->start);
5866
0
}
5867
5868
/**
5869
 * xmlAutomataSetFinalState:
5870
 * @am: an automata
5871
 * @state: a state in this automata
5872
 *
5873
 * Makes that state a final state
5874
 *
5875
 * Returns 0 or -1 in case of error
5876
 */
5877
int
5878
0
xmlAutomataSetFinalState(xmlAutomataPtr am, xmlAutomataStatePtr state) {
5879
0
    if ((am == NULL) || (state == NULL))
5880
0
  return(-1);
5881
0
    state->type = XML_REGEXP_FINAL_STATE;
5882
0
    return(0);
5883
0
}
5884
5885
/**
5886
 * xmlAutomataNewTransition:
5887
 * @am: an automata
5888
 * @from: the starting point of the transition
5889
 * @to: the target point of the transition or NULL
5890
 * @token: the input string associated to that transition
5891
 * @data: data passed to the callback function if the transition is activated
5892
 *
5893
 * If @to is NULL, this creates first a new target state in the automata
5894
 * and then adds a transition from the @from state to the target state
5895
 * activated by the value of @token
5896
 *
5897
 * Returns the target state or NULL in case of error
5898
 */
5899
xmlAutomataStatePtr
5900
xmlAutomataNewTransition(xmlAutomataPtr am, xmlAutomataStatePtr from,
5901
       xmlAutomataStatePtr to, const xmlChar *token,
5902
0
       void *data) {
5903
0
    xmlRegAtomPtr atom;
5904
5905
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
5906
0
  return(NULL);
5907
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5908
0
    if (atom == NULL)
5909
0
        return(NULL);
5910
0
    atom->data = data;
5911
0
    atom->valuep = xmlStrdup(token);
5912
5913
0
    if (xmlFAGenerateTransitions(am, from, to, atom) < 0) {
5914
0
        xmlRegFreeAtom(atom);
5915
0
  return(NULL);
5916
0
    }
5917
0
    if (to == NULL)
5918
0
  return(am->state);
5919
0
    return(to);
5920
0
}
5921
5922
/**
5923
 * xmlAutomataNewTransition2:
5924
 * @am: an automata
5925
 * @from: the starting point of the transition
5926
 * @to: the target point of the transition or NULL
5927
 * @token: the first input string associated to that transition
5928
 * @token2: the second input string associated to that transition
5929
 * @data: data passed to the callback function if the transition is activated
5930
 *
5931
 * If @to is NULL, this creates first a new target state in the automata
5932
 * and then adds a transition from the @from state to the target state
5933
 * activated by the value of @token
5934
 *
5935
 * Returns the target state or NULL in case of error
5936
 */
5937
xmlAutomataStatePtr
5938
xmlAutomataNewTransition2(xmlAutomataPtr am, xmlAutomataStatePtr from,
5939
        xmlAutomataStatePtr to, const xmlChar *token,
5940
0
        const xmlChar *token2, void *data) {
5941
0
    xmlRegAtomPtr atom;
5942
5943
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
5944
0
  return(NULL);
5945
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
5946
0
    if (atom == NULL)
5947
0
  return(NULL);
5948
0
    atom->data = data;
5949
0
    if ((token2 == NULL) || (*token2 == 0)) {
5950
0
  atom->valuep = xmlStrdup(token);
5951
0
    } else {
5952
0
  int lenn, lenp;
5953
0
  xmlChar *str;
5954
5955
0
  lenn = strlen((char *) token2);
5956
0
  lenp = strlen((char *) token);
5957
5958
0
  str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
5959
0
  if (str == NULL) {
5960
0
      xmlRegFreeAtom(atom);
5961
0
      return(NULL);
5962
0
  }
5963
0
  memcpy(&str[0], token, lenp);
5964
0
  str[lenp] = '|';
5965
0
  memcpy(&str[lenp + 1], token2, lenn);
5966
0
  str[lenn + lenp + 1] = 0;
5967
5968
0
  atom->valuep = str;
5969
0
    }
5970
5971
0
    if (xmlFAGenerateTransitions(am, from, to, atom) < 0) {
5972
0
        xmlRegFreeAtom(atom);
5973
0
  return(NULL);
5974
0
    }
5975
0
    if (to == NULL)
5976
0
  return(am->state);
5977
0
    return(to);
5978
0
}
5979
5980
/**
5981
 * xmlAutomataNewNegTrans:
5982
 * @am: an automata
5983
 * @from: the starting point of the transition
5984
 * @to: the target point of the transition or NULL
5985
 * @token: the first input string associated to that transition
5986
 * @token2: the second input string associated to that transition
5987
 * @data: data passed to the callback function if the transition is activated
5988
 *
5989
 * If @to is NULL, this creates first a new target state in the automata
5990
 * and then adds a transition from the @from state to the target state
5991
 * activated by any value except (@token,@token2)
5992
 * Note that if @token2 is not NULL, then (X, NULL) won't match to follow
5993
 # the semantic of XSD ##other
5994
 *
5995
 * Returns the target state or NULL in case of error
5996
 */
5997
xmlAutomataStatePtr
5998
xmlAutomataNewNegTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
5999
           xmlAutomataStatePtr to, const xmlChar *token,
6000
0
           const xmlChar *token2, void *data) {
6001
0
    xmlRegAtomPtr atom;
6002
0
    xmlChar err_msg[200];
6003
6004
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
6005
0
  return(NULL);
6006
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
6007
0
    if (atom == NULL)
6008
0
  return(NULL);
6009
0
    atom->data = data;
6010
0
    atom->neg = 1;
6011
0
    if ((token2 == NULL) || (*token2 == 0)) {
6012
0
  atom->valuep = xmlStrdup(token);
6013
0
    } else {
6014
0
  int lenn, lenp;
6015
0
  xmlChar *str;
6016
6017
0
  lenn = strlen((char *) token2);
6018
0
  lenp = strlen((char *) token);
6019
6020
0
  str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
6021
0
  if (str == NULL) {
6022
0
      xmlRegFreeAtom(atom);
6023
0
      return(NULL);
6024
0
  }
6025
0
  memcpy(&str[0], token, lenp);
6026
0
  str[lenp] = '|';
6027
0
  memcpy(&str[lenp + 1], token2, lenn);
6028
0
  str[lenn + lenp + 1] = 0;
6029
6030
0
  atom->valuep = str;
6031
0
    }
6032
0
    snprintf((char *) err_msg, 199, "not %s", (const char *) atom->valuep);
6033
0
    err_msg[199] = 0;
6034
0
    atom->valuep2 = xmlStrdup(err_msg);
6035
6036
0
    if (xmlFAGenerateTransitions(am, from, to, atom) < 0) {
6037
0
        xmlRegFreeAtom(atom);
6038
0
  return(NULL);
6039
0
    }
6040
0
    am->negs++;
6041
0
    if (to == NULL)
6042
0
  return(am->state);
6043
0
    return(to);
6044
0
}
6045
6046
/**
6047
 * xmlAutomataNewCountTrans2:
6048
 * @am: an automata
6049
 * @from: the starting point of the transition
6050
 * @to: the target point of the transition or NULL
6051
 * @token: the input string associated to that transition
6052
 * @token2: the second input string associated to that transition
6053
 * @min:  the minimum successive occurrences of token
6054
 * @max:  the maximum successive occurrences of token
6055
 * @data:  data associated to the transition
6056
 *
6057
 * If @to is NULL, this creates first a new target state in the automata
6058
 * and then adds a transition from the @from state to the target state
6059
 * activated by a succession of input of value @token and @token2 and
6060
 * whose number is between @min and @max
6061
 *
6062
 * Returns the target state or NULL in case of error
6063
 */
6064
xmlAutomataStatePtr
6065
xmlAutomataNewCountTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from,
6066
       xmlAutomataStatePtr to, const xmlChar *token,
6067
       const xmlChar *token2,
6068
0
       int min, int max, void *data) {
6069
0
    xmlRegAtomPtr atom;
6070
0
    int counter;
6071
6072
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
6073
0
  return(NULL);
6074
0
    if (min < 0)
6075
0
  return(NULL);
6076
0
    if ((max < min) || (max < 1))
6077
0
  return(NULL);
6078
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
6079
0
    if (atom == NULL)
6080
0
  return(NULL);
6081
0
    if ((token2 == NULL) || (*token2 == 0)) {
6082
0
  atom->valuep = xmlStrdup(token);
6083
0
        if (atom->valuep == NULL)
6084
0
            goto error;
6085
0
    } else {
6086
0
  int lenn, lenp;
6087
0
  xmlChar *str;
6088
6089
0
  lenn = strlen((char *) token2);
6090
0
  lenp = strlen((char *) token);
6091
6092
0
  str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
6093
0
  if (str == NULL)
6094
0
      goto error;
6095
0
  memcpy(&str[0], token, lenp);
6096
0
  str[lenp] = '|';
6097
0
  memcpy(&str[lenp + 1], token2, lenn);
6098
0
  str[lenn + lenp + 1] = 0;
6099
6100
0
  atom->valuep = str;
6101
0
    }
6102
0
    atom->data = data;
6103
0
    if (min == 0)
6104
0
  atom->min = 1;
6105
0
    else
6106
0
  atom->min = min;
6107
0
    atom->max = max;
6108
6109
    /*
6110
     * associate a counter to the transition.
6111
     */
6112
0
    counter = xmlRegGetCounter(am);
6113
0
    if (counter < 0)
6114
0
        goto error;
6115
0
    am->counters[counter].min = min;
6116
0
    am->counters[counter].max = max;
6117
6118
    /* xmlFAGenerateTransitions(am, from, to, atom); */
6119
0
    if (to == NULL) {
6120
0
  to = xmlRegStatePush(am);
6121
0
        if (to == NULL)
6122
0
            goto error;
6123
0
    }
6124
0
    xmlRegStateAddTrans(am, from, atom, to, counter, -1);
6125
0
    if (xmlRegAtomPush(am, atom) < 0)
6126
0
        goto error;
6127
0
    am->state = to;
6128
6129
0
    if (to == NULL)
6130
0
  to = am->state;
6131
0
    if (to == NULL)
6132
0
  return(NULL);
6133
0
    if (min == 0)
6134
0
  xmlFAGenerateEpsilonTransition(am, from, to);
6135
0
    return(to);
6136
6137
0
error:
6138
0
    xmlRegFreeAtom(atom);
6139
0
    return(NULL);
6140
0
}
6141
6142
/**
6143
 * xmlAutomataNewCountTrans:
6144
 * @am: an automata
6145
 * @from: the starting point of the transition
6146
 * @to: the target point of the transition or NULL
6147
 * @token: the input string associated to that transition
6148
 * @min:  the minimum successive occurrences of token
6149
 * @max:  the maximum successive occurrences of token
6150
 * @data:  data associated to the transition
6151
 *
6152
 * If @to is NULL, this creates first a new target state in the automata
6153
 * and then adds a transition from the @from state to the target state
6154
 * activated by a succession of input of value @token and whose number
6155
 * is between @min and @max
6156
 *
6157
 * Returns the target state or NULL in case of error
6158
 */
6159
xmlAutomataStatePtr
6160
xmlAutomataNewCountTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6161
       xmlAutomataStatePtr to, const xmlChar *token,
6162
0
       int min, int max, void *data) {
6163
0
    xmlRegAtomPtr atom;
6164
0
    int counter;
6165
6166
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
6167
0
  return(NULL);
6168
0
    if (min < 0)
6169
0
  return(NULL);
6170
0
    if ((max < min) || (max < 1))
6171
0
  return(NULL);
6172
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
6173
0
    if (atom == NULL)
6174
0
  return(NULL);
6175
0
    atom->valuep = xmlStrdup(token);
6176
0
    if (atom->valuep == NULL)
6177
0
        goto error;
6178
0
    atom->data = data;
6179
0
    if (min == 0)
6180
0
  atom->min = 1;
6181
0
    else
6182
0
  atom->min = min;
6183
0
    atom->max = max;
6184
6185
    /*
6186
     * associate a counter to the transition.
6187
     */
6188
0
    counter = xmlRegGetCounter(am);
6189
0
    if (counter < 0)
6190
0
        goto error;
6191
0
    am->counters[counter].min = min;
6192
0
    am->counters[counter].max = max;
6193
6194
    /* xmlFAGenerateTransitions(am, from, to, atom); */
6195
0
    if (to == NULL) {
6196
0
  to = xmlRegStatePush(am);
6197
0
        if (to == NULL)
6198
0
            goto error;
6199
0
    }
6200
0
    xmlRegStateAddTrans(am, from, atom, to, counter, -1);
6201
0
    if (xmlRegAtomPush(am, atom) < 0)
6202
0
        goto error;
6203
0
    am->state = to;
6204
6205
0
    if (to == NULL)
6206
0
  to = am->state;
6207
0
    if (to == NULL)
6208
0
  return(NULL);
6209
0
    if (min == 0)
6210
0
  xmlFAGenerateEpsilonTransition(am, from, to);
6211
0
    return(to);
6212
6213
0
error:
6214
0
    xmlRegFreeAtom(atom);
6215
0
    return(NULL);
6216
0
}
6217
6218
/**
6219
 * xmlAutomataNewOnceTrans2:
6220
 * @am: an automata
6221
 * @from: the starting point of the transition
6222
 * @to: the target point of the transition or NULL
6223
 * @token: the input string associated to that transition
6224
 * @token2: the second input string associated to that transition
6225
 * @min:  the minimum successive occurrences of token
6226
 * @max:  the maximum successive occurrences of token
6227
 * @data:  data associated to the transition
6228
 *
6229
 * If @to is NULL, this creates first a new target state in the automata
6230
 * and then adds a transition from the @from state to the target state
6231
 * activated by a succession of input of value @token and @token2 and whose
6232
 * number is between @min and @max, moreover that transition can only be
6233
 * crossed once.
6234
 *
6235
 * Returns the target state or NULL in case of error
6236
 */
6237
xmlAutomataStatePtr
6238
xmlAutomataNewOnceTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from,
6239
       xmlAutomataStatePtr to, const xmlChar *token,
6240
       const xmlChar *token2,
6241
0
       int min, int max, void *data) {
6242
0
    xmlRegAtomPtr atom;
6243
0
    int counter;
6244
6245
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
6246
0
  return(NULL);
6247
0
    if (min < 1)
6248
0
  return(NULL);
6249
0
    if (max < min)
6250
0
  return(NULL);
6251
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
6252
0
    if (atom == NULL)
6253
0
  return(NULL);
6254
0
    if ((token2 == NULL) || (*token2 == 0)) {
6255
0
  atom->valuep = xmlStrdup(token);
6256
0
        if (atom->valuep == NULL)
6257
0
            goto error;
6258
0
    } else {
6259
0
  int lenn, lenp;
6260
0
  xmlChar *str;
6261
6262
0
  lenn = strlen((char *) token2);
6263
0
  lenp = strlen((char *) token);
6264
6265
0
  str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
6266
0
  if (str == NULL)
6267
0
      goto error;
6268
0
  memcpy(&str[0], token, lenp);
6269
0
  str[lenp] = '|';
6270
0
  memcpy(&str[lenp + 1], token2, lenn);
6271
0
  str[lenn + lenp + 1] = 0;
6272
6273
0
  atom->valuep = str;
6274
0
    }
6275
0
    atom->data = data;
6276
0
    atom->quant = XML_REGEXP_QUANT_ONCEONLY;
6277
0
    atom->min = min;
6278
0
    atom->max = max;
6279
    /*
6280
     * associate a counter to the transition.
6281
     */
6282
0
    counter = xmlRegGetCounter(am);
6283
0
    if (counter < 0)
6284
0
        goto error;
6285
0
    am->counters[counter].min = 1;
6286
0
    am->counters[counter].max = 1;
6287
6288
    /* xmlFAGenerateTransitions(am, from, to, atom); */
6289
0
    if (to == NULL) {
6290
0
  to = xmlRegStatePush(am);
6291
0
        if (to == NULL)
6292
0
            goto error;
6293
0
    }
6294
0
    xmlRegStateAddTrans(am, from, atom, to, counter, -1);
6295
0
    if (xmlRegAtomPush(am, atom) < 0)
6296
0
        goto error;
6297
0
    am->state = to;
6298
0
    return(to);
6299
6300
0
error:
6301
0
    xmlRegFreeAtom(atom);
6302
0
    return(NULL);
6303
0
}
6304
6305
6306
6307
/**
6308
 * xmlAutomataNewOnceTrans:
6309
 * @am: an automata
6310
 * @from: the starting point of the transition
6311
 * @to: the target point of the transition or NULL
6312
 * @token: the input string associated to that transition
6313
 * @min:  the minimum successive occurrences of token
6314
 * @max:  the maximum successive occurrences of token
6315
 * @data:  data associated to the transition
6316
 *
6317
 * If @to is NULL, this creates first a new target state in the automata
6318
 * and then adds a transition from the @from state to the target state
6319
 * activated by a succession of input of value @token and whose number
6320
 * is between @min and @max, moreover that transition can only be crossed
6321
 * once.
6322
 *
6323
 * Returns the target state or NULL in case of error
6324
 */
6325
xmlAutomataStatePtr
6326
xmlAutomataNewOnceTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6327
       xmlAutomataStatePtr to, const xmlChar *token,
6328
0
       int min, int max, void *data) {
6329
0
    xmlRegAtomPtr atom;
6330
0
    int counter;
6331
6332
0
    if ((am == NULL) || (from == NULL) || (token == NULL))
6333
0
  return(NULL);
6334
0
    if (min < 1)
6335
0
  return(NULL);
6336
0
    if (max < min)
6337
0
  return(NULL);
6338
0
    atom = xmlRegNewAtom(am, XML_REGEXP_STRING);
6339
0
    if (atom == NULL)
6340
0
  return(NULL);
6341
0
    atom->valuep = xmlStrdup(token);
6342
0
    atom->data = data;
6343
0
    atom->quant = XML_REGEXP_QUANT_ONCEONLY;
6344
0
    atom->min = min;
6345
0
    atom->max = max;
6346
    /*
6347
     * associate a counter to the transition.
6348
     */
6349
0
    counter = xmlRegGetCounter(am);
6350
0
    if (counter < 0)
6351
0
        goto error;
6352
0
    am->counters[counter].min = 1;
6353
0
    am->counters[counter].max = 1;
6354
6355
    /* xmlFAGenerateTransitions(am, from, to, atom); */
6356
0
    if (to == NULL) {
6357
0
  to = xmlRegStatePush(am);
6358
0
        if (to == NULL)
6359
0
            goto error;
6360
0
    }
6361
0
    xmlRegStateAddTrans(am, from, atom, to, counter, -1);
6362
0
    if (xmlRegAtomPush(am, atom) < 0)
6363
0
        goto error;
6364
0
    am->state = to;
6365
0
    return(to);
6366
6367
0
error:
6368
0
    xmlRegFreeAtom(atom);
6369
0
    return(NULL);
6370
0
}
6371
6372
/**
6373
 * xmlAutomataNewState:
6374
 * @am: an automata
6375
 *
6376
 * Create a new disconnected state in the automata
6377
 *
6378
 * Returns the new state or NULL in case of error
6379
 */
6380
xmlAutomataStatePtr
6381
0
xmlAutomataNewState(xmlAutomataPtr am) {
6382
0
    if (am == NULL)
6383
0
  return(NULL);
6384
0
    return(xmlRegStatePush(am));
6385
0
}
6386
6387
/**
6388
 * xmlAutomataNewEpsilon:
6389
 * @am: an automata
6390
 * @from: the starting point of the transition
6391
 * @to: the target point of the transition or NULL
6392
 *
6393
 * If @to is NULL, this creates first a new target state in the automata
6394
 * and then adds an epsilon transition from the @from state to the
6395
 * target state
6396
 *
6397
 * Returns the target state or NULL in case of error
6398
 */
6399
xmlAutomataStatePtr
6400
xmlAutomataNewEpsilon(xmlAutomataPtr am, xmlAutomataStatePtr from,
6401
0
          xmlAutomataStatePtr to) {
6402
0
    if ((am == NULL) || (from == NULL))
6403
0
  return(NULL);
6404
0
    xmlFAGenerateEpsilonTransition(am, from, to);
6405
0
    if (to == NULL)
6406
0
  return(am->state);
6407
0
    return(to);
6408
0
}
6409
6410
/**
6411
 * xmlAutomataNewAllTrans:
6412
 * @am: an automata
6413
 * @from: the starting point of the transition
6414
 * @to: the target point of the transition or NULL
6415
 * @lax: allow to transition if not all all transitions have been activated
6416
 *
6417
 * If @to is NULL, this creates first a new target state in the automata
6418
 * and then adds a an ALL transition from the @from state to the
6419
 * target state. That transition is an epsilon transition allowed only when
6420
 * all transitions from the @from node have been activated.
6421
 *
6422
 * Returns the target state or NULL in case of error
6423
 */
6424
xmlAutomataStatePtr
6425
xmlAutomataNewAllTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6426
0
           xmlAutomataStatePtr to, int lax) {
6427
0
    if ((am == NULL) || (from == NULL))
6428
0
  return(NULL);
6429
0
    xmlFAGenerateAllTransition(am, from, to, lax);
6430
0
    if (to == NULL)
6431
0
  return(am->state);
6432
0
    return(to);
6433
0
}
6434
6435
/**
6436
 * xmlAutomataNewCounter:
6437
 * @am: an automata
6438
 * @min:  the minimal value on the counter
6439
 * @max:  the maximal value on the counter
6440
 *
6441
 * Create a new counter
6442
 *
6443
 * Returns the counter number or -1 in case of error
6444
 */
6445
int
6446
0
xmlAutomataNewCounter(xmlAutomataPtr am, int min, int max) {
6447
0
    int ret;
6448
6449
0
    if (am == NULL)
6450
0
  return(-1);
6451
6452
0
    ret = xmlRegGetCounter(am);
6453
0
    if (ret < 0)
6454
0
  return(-1);
6455
0
    am->counters[ret].min = min;
6456
0
    am->counters[ret].max = max;
6457
0
    return(ret);
6458
0
}
6459
6460
/**
6461
 * xmlAutomataNewCountedTrans:
6462
 * @am: an automata
6463
 * @from: the starting point of the transition
6464
 * @to: the target point of the transition or NULL
6465
 * @counter: the counter associated to that transition
6466
 *
6467
 * If @to is NULL, this creates first a new target state in the automata
6468
 * and then adds an epsilon transition from the @from state to the target state
6469
 * which will increment the counter provided
6470
 *
6471
 * Returns the target state or NULL in case of error
6472
 */
6473
xmlAutomataStatePtr
6474
xmlAutomataNewCountedTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6475
0
    xmlAutomataStatePtr to, int counter) {
6476
0
    if ((am == NULL) || (from == NULL) || (counter < 0))
6477
0
  return(NULL);
6478
0
    xmlFAGenerateCountedEpsilonTransition(am, from, to, counter);
6479
0
    if (to == NULL)
6480
0
  return(am->state);
6481
0
    return(to);
6482
0
}
6483
6484
/**
6485
 * xmlAutomataNewCounterTrans:
6486
 * @am: an automata
6487
 * @from: the starting point of the transition
6488
 * @to: the target point of the transition or NULL
6489
 * @counter: the counter associated to that transition
6490
 *
6491
 * If @to is NULL, this creates first a new target state in the automata
6492
 * and then adds an epsilon transition from the @from state to the target state
6493
 * which will be allowed only if the counter is within the right range.
6494
 *
6495
 * Returns the target state or NULL in case of error
6496
 */
6497
xmlAutomataStatePtr
6498
xmlAutomataNewCounterTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
6499
0
    xmlAutomataStatePtr to, int counter) {
6500
0
    if ((am == NULL) || (from == NULL) || (counter < 0))
6501
0
  return(NULL);
6502
0
    xmlFAGenerateCountedTransition(am, from, to, counter);
6503
0
    if (to == NULL)
6504
0
  return(am->state);
6505
0
    return(to);
6506
0
}
6507
6508
/**
6509
 * xmlAutomataCompile:
6510
 * @am: an automata
6511
 *
6512
 * Compile the automata into a Reg Exp ready for being executed.
6513
 * The automata should be free after this point.
6514
 *
6515
 * Returns the compiled regexp or NULL in case of error
6516
 */
6517
xmlRegexpPtr
6518
0
xmlAutomataCompile(xmlAutomataPtr am) {
6519
0
    xmlRegexpPtr ret;
6520
6521
0
    if ((am == NULL) || (am->error != 0)) return(NULL);
6522
0
    xmlFAEliminateEpsilonTransitions(am);
6523
    /* xmlFAComputesDeterminism(am); */
6524
0
    ret = xmlRegEpxFromParse(am);
6525
6526
0
    return(ret);
6527
0
}
6528
6529
/**
6530
 * xmlAutomataIsDeterminist:
6531
 * @am: an automata
6532
 *
6533
 * Checks if an automata is determinist.
6534
 *
6535
 * Returns 1 if true, 0 if not, and -1 in case of error
6536
 */
6537
int
6538
0
xmlAutomataIsDeterminist(xmlAutomataPtr am) {
6539
0
    int ret;
6540
6541
0
    if (am == NULL)
6542
0
  return(-1);
6543
6544
0
    ret = xmlFAComputesDeterminism(am);
6545
0
    return(ret);
6546
0
}
6547
#endif /* LIBXML_AUTOMATA_ENABLED */
6548
6549
#ifdef LIBXML_EXPR_ENABLED
6550
/************************************************************************
6551
 *                  *
6552
 *    Formal Expression handling code       *
6553
 *                  *
6554
 ************************************************************************/
6555
/************************************************************************
6556
 *                  *
6557
 *    Expression handling context       *
6558
 *                  *
6559
 ************************************************************************/
6560
6561
struct _xmlExpCtxt {
6562
    xmlDictPtr dict;
6563
    xmlExpNodePtr *table;
6564
    int size;
6565
    int nbElems;
6566
    int nb_nodes;
6567
    int maxNodes;
6568
    const char *expr;
6569
    const char *cur;
6570
    int nb_cons;
6571
    int tabSize;
6572
};
6573
6574
/**
6575
 * xmlExpNewCtxt:
6576
 * @maxNodes:  the maximum number of nodes
6577
 * @dict:  optional dictionary to use internally
6578
 *
6579
 * Creates a new context for manipulating expressions
6580
 *
6581
 * Returns the context or NULL in case of error
6582
 */
6583
xmlExpCtxtPtr
6584
xmlExpNewCtxt(int maxNodes, xmlDictPtr dict) {
6585
    xmlExpCtxtPtr ret;
6586
    int size = 256;
6587
6588
    if (maxNodes <= 4096)
6589
        maxNodes = 4096;
6590
6591
    ret = (xmlExpCtxtPtr) xmlMalloc(sizeof(xmlExpCtxt));
6592
    if (ret == NULL)
6593
        return(NULL);
6594
    memset(ret, 0, sizeof(xmlExpCtxt));
6595
    ret->size = size;
6596
    ret->nbElems = 0;
6597
    ret->maxNodes = maxNodes;
6598
    ret->table = xmlMalloc(size * sizeof(xmlExpNodePtr));
6599
    if (ret->table == NULL) {
6600
        xmlFree(ret);
6601
  return(NULL);
6602
    }
6603
    memset(ret->table, 0, size * sizeof(xmlExpNodePtr));
6604
    if (dict == NULL) {
6605
        ret->dict = xmlDictCreate();
6606
  if (ret->dict == NULL) {
6607
      xmlFree(ret->table);
6608
      xmlFree(ret);
6609
      return(NULL);
6610
  }
6611
    } else {
6612
        ret->dict = dict;
6613
  xmlDictReference(ret->dict);
6614
    }
6615
    return(ret);
6616
}
6617
6618
/**
6619
 * xmlExpFreeCtxt:
6620
 * @ctxt:  an expression context
6621
 *
6622
 * Free an expression context
6623
 */
6624
void
6625
xmlExpFreeCtxt(xmlExpCtxtPtr ctxt) {
6626
    if (ctxt == NULL)
6627
        return;
6628
    xmlDictFree(ctxt->dict);
6629
    if (ctxt->table != NULL)
6630
  xmlFree(ctxt->table);
6631
    xmlFree(ctxt);
6632
}
6633
6634
/************************************************************************
6635
 *                  *
6636
 *    Structure associated to an expression node    *
6637
 *                  *
6638
 ************************************************************************/
6639
#define MAX_NODES 10000
6640
6641
/* #define DEBUG_DERIV */
6642
6643
/*
6644
 * TODO:
6645
 * - Wildcards
6646
 * - public API for creation
6647
 *
6648
 * Started
6649
 * - regression testing
6650
 *
6651
 * Done
6652
 * - split into module and test tool
6653
 * - memleaks
6654
 */
6655
6656
typedef enum {
6657
    XML_EXP_NILABLE = (1 << 0)
6658
} xmlExpNodeInfo;
6659
6660
#define IS_NILLABLE(node) ((node)->info & XML_EXP_NILABLE)
6661
6662
struct _xmlExpNode {
6663
    unsigned char type;/* xmlExpNodeType */
6664
    unsigned char info;/* OR of xmlExpNodeInfo */
6665
    unsigned short key; /* the hash key */
6666
    unsigned int ref; /* The number of references */
6667
    int c_max;    /* the maximum length it can consume */
6668
    xmlExpNodePtr exp_left;
6669
    xmlExpNodePtr next;/* the next node in the hash table or free list */
6670
    union {
6671
  struct {
6672
      int f_min;
6673
      int f_max;
6674
  } count;
6675
  struct {
6676
      xmlExpNodePtr f_right;
6677
  } children;
6678
        const xmlChar *f_str;
6679
    } field;
6680
};
6681
6682
#define exp_min field.count.f_min
6683
#define exp_max field.count.f_max
6684
/* #define exp_left field.children.f_left */
6685
#define exp_right field.children.f_right
6686
#define exp_str field.f_str
6687
6688
static xmlExpNodePtr xmlExpNewNode(xmlExpCtxtPtr ctxt, xmlExpNodeType type);
6689
static xmlExpNode forbiddenExpNode = {
6690
    XML_EXP_FORBID, 0, 0, 0, 0, NULL, NULL, {{ 0, 0}}
6691
};
6692
xmlExpNodePtr forbiddenExp = &forbiddenExpNode;
6693
static xmlExpNode emptyExpNode = {
6694
    XML_EXP_EMPTY, 1, 0, 0, 0, NULL, NULL, {{ 0, 0}}
6695
};
6696
xmlExpNodePtr emptyExp = &emptyExpNode;
6697
6698
/************************************************************************
6699
 *                  *
6700
 *  The custom hash table for unicity and canonicalization    *
6701
 *  of sub-expressions pointers           *
6702
 *                  *
6703
 ************************************************************************/
6704
/*
6705
 * xmlExpHashNameComputeKey:
6706
 * Calculate the hash key for a token
6707
 */
6708
static unsigned short
6709
xmlExpHashNameComputeKey(const xmlChar *name) {
6710
    unsigned short value = 0L;
6711
    char ch;
6712
6713
    if (name != NULL) {
6714
  value += 30 * (*name);
6715
  while ((ch = *name++) != 0) {
6716
      value = value ^ ((value << 5) + (value >> 3) + (unsigned long)ch);
6717
  }
6718
    }
6719
    return (value);
6720
}
6721
6722
/*
6723
 * xmlExpHashComputeKey:
6724
 * Calculate the hash key for a compound expression
6725
 */
6726
static unsigned short
6727
xmlExpHashComputeKey(xmlExpNodeType type, xmlExpNodePtr left,
6728
                     xmlExpNodePtr right) {
6729
    unsigned long value;
6730
    unsigned short ret;
6731
6732
    switch (type) {
6733
        case XML_EXP_SEQ:
6734
      value = left->key;
6735
      value += right->key;
6736
      value *= 3;
6737
      ret = (unsigned short) value;
6738
      break;
6739
        case XML_EXP_OR:
6740
      value = left->key;
6741
      value += right->key;
6742
      value *= 7;
6743
      ret = (unsigned short) value;
6744
      break;
6745
        case XML_EXP_COUNT:
6746
      value = left->key;
6747
      value += right->key;
6748
      ret = (unsigned short) value;
6749
      break;
6750
  default:
6751
      ret = 0;
6752
    }
6753
    return(ret);
6754
}
6755
6756
6757
static xmlExpNodePtr
6758
xmlExpNewNode(xmlExpCtxtPtr ctxt, xmlExpNodeType type) {
6759
    xmlExpNodePtr ret;
6760
6761
    if (ctxt->nb_nodes >= MAX_NODES)
6762
        return(NULL);
6763
    ret = (xmlExpNodePtr) xmlMalloc(sizeof(xmlExpNode));
6764
    if (ret == NULL)
6765
        return(NULL);
6766
    memset(ret, 0, sizeof(xmlExpNode));
6767
    ret->type = type;
6768
    ret->next = NULL;
6769
    ctxt->nb_nodes++;
6770
    ctxt->nb_cons++;
6771
    return(ret);
6772
}
6773
6774
/**
6775
 * xmlExpHashGetEntry:
6776
 * @table: the hash table
6777
 *
6778
 * Get the unique entry from the hash table. The entry is created if
6779
 * needed. @left and @right are consumed, i.e. their ref count will
6780
 * be decremented by the operation.
6781
 *
6782
 * Returns the pointer or NULL in case of error
6783
 */
6784
static xmlExpNodePtr
6785
xmlExpHashGetEntry(xmlExpCtxtPtr ctxt, xmlExpNodeType type,
6786
                   xmlExpNodePtr left, xmlExpNodePtr right,
6787
       const xmlChar *name, int min, int max) {
6788
    unsigned short kbase, key;
6789
    xmlExpNodePtr entry;
6790
    xmlExpNodePtr insert;
6791
6792
    if (ctxt == NULL)
6793
  return(NULL);
6794
6795
    /*
6796
     * Check for duplicate and insertion location.
6797
     */
6798
    if (type == XML_EXP_ATOM) {
6799
  kbase = xmlExpHashNameComputeKey(name);
6800
    } else if (type == XML_EXP_COUNT) {
6801
        /* COUNT reduction rule 1 */
6802
  /* a{1} -> a */
6803
  if (min == max) {
6804
      if (min == 1) {
6805
    return(left);
6806
      }
6807
      if (min == 0) {
6808
    xmlExpFree(ctxt, left);
6809
          return(emptyExp);
6810
      }
6811
  }
6812
  if (min < 0) {
6813
      xmlExpFree(ctxt, left);
6814
      return(forbiddenExp);
6815
  }
6816
        if (max == -1)
6817
      kbase = min + 79;
6818
  else
6819
      kbase = max - min;
6820
  kbase += left->key;
6821
    } else if (type == XML_EXP_OR) {
6822
        /* Forbid reduction rules */
6823
        if (left->type == XML_EXP_FORBID) {
6824
      xmlExpFree(ctxt, left);
6825
      return(right);
6826
  }
6827
        if (right->type == XML_EXP_FORBID) {
6828
      xmlExpFree(ctxt, right);
6829
      return(left);
6830
  }
6831
6832
        /* OR reduction rule 1 */
6833
  /* a | a reduced to a */
6834
        if (left == right) {
6835
      xmlExpFree(ctxt, right);
6836
      return(left);
6837
  }
6838
        /* OR canonicalization rule 1 */
6839
  /* linearize (a | b) | c into a | (b | c) */
6840
        if ((left->type == XML_EXP_OR) && (right->type != XML_EXP_OR)) {
6841
      xmlExpNodePtr tmp = left;
6842
            left = right;
6843
      right = tmp;
6844
  }
6845
        /* OR reduction rule 2 */
6846
  /* a | (a | b) and b | (a | b) are reduced to a | b */
6847
        if (right->type == XML_EXP_OR) {
6848
      if ((left == right->exp_left) ||
6849
          (left == right->exp_right)) {
6850
    xmlExpFree(ctxt, left);
6851
    return(right);
6852
      }
6853
  }
6854
        /* OR canonicalization rule 2 */
6855
  /* linearize (a | b) | c into a | (b | c) */
6856
        if (left->type == XML_EXP_OR) {
6857
      xmlExpNodePtr tmp;
6858
6859
      /* OR canonicalization rule 2 */
6860
      if ((left->exp_right->type != XML_EXP_OR) &&
6861
          (left->exp_right->key < left->exp_left->key)) {
6862
          tmp = left->exp_right;
6863
    left->exp_right = left->exp_left;
6864
    left->exp_left = tmp;
6865
      }
6866
      left->exp_right->ref++;
6867
      tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left->exp_right, right,
6868
                               NULL, 0, 0);
6869
      left->exp_left->ref++;
6870
      tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left->exp_left, tmp,
6871
                               NULL, 0, 0);
6872
6873
      xmlExpFree(ctxt, left);
6874
      return(tmp);
6875
  }
6876
  if (right->type == XML_EXP_OR) {
6877
      /* Ordering in the tree */
6878
      /* C | (A | B) -> A | (B | C) */
6879
      if (left->key > right->exp_right->key) {
6880
    xmlExpNodePtr tmp;
6881
    right->exp_right->ref++;
6882
    tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_right,
6883
                             left, NULL, 0, 0);
6884
    right->exp_left->ref++;
6885
    tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_left,
6886
                             tmp, NULL, 0, 0);
6887
    xmlExpFree(ctxt, right);
6888
    return(tmp);
6889
      }
6890
      /* Ordering in the tree */
6891
      /* B | (A | C) -> A | (B | C) */
6892
      if (left->key > right->exp_left->key) {
6893
    xmlExpNodePtr tmp;
6894
    right->exp_right->ref++;
6895
    tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left,
6896
                             right->exp_right, NULL, 0, 0);
6897
    right->exp_left->ref++;
6898
    tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_left,
6899
                             tmp, NULL, 0, 0);
6900
    xmlExpFree(ctxt, right);
6901
    return(tmp);
6902
      }
6903
  }
6904
  /* we know both types are != XML_EXP_OR here */
6905
        else if (left->key > right->key) {
6906
      xmlExpNodePtr tmp = left;
6907
            left = right;
6908
      right = tmp;
6909
  }
6910
  kbase = xmlExpHashComputeKey(type, left, right);
6911
    } else if (type == XML_EXP_SEQ) {
6912
        /* Forbid reduction rules */
6913
        if (left->type == XML_EXP_FORBID) {
6914
      xmlExpFree(ctxt, right);
6915
      return(left);
6916
  }
6917
        if (right->type == XML_EXP_FORBID) {
6918
      xmlExpFree(ctxt, left);
6919
      return(right);
6920
  }
6921
        /* Empty reduction rules */
6922
        if (right->type == XML_EXP_EMPTY) {
6923
      return(left);
6924
  }
6925
        if (left->type == XML_EXP_EMPTY) {
6926
      return(right);
6927
  }
6928
  kbase = xmlExpHashComputeKey(type, left, right);
6929
    } else
6930
        return(NULL);
6931
6932
    key = kbase % ctxt->size;
6933
    if (ctxt->table[key] != NULL) {
6934
  for (insert = ctxt->table[key]; insert != NULL;
6935
       insert = insert->next) {
6936
      if ((insert->key == kbase) &&
6937
          (insert->type == type)) {
6938
    if (type == XML_EXP_ATOM) {
6939
        if (name == insert->exp_str) {
6940
      insert->ref++;
6941
      return(insert);
6942
        }
6943
    } else if (type == XML_EXP_COUNT) {
6944
        if ((insert->exp_min == min) && (insert->exp_max == max) &&
6945
            (insert->exp_left == left)) {
6946
      insert->ref++;
6947
      left->ref--;
6948
      return(insert);
6949
        }
6950
    } else if ((insert->exp_left == left) &&
6951
         (insert->exp_right == right)) {
6952
        insert->ref++;
6953
        left->ref--;
6954
        right->ref--;
6955
        return(insert);
6956
    }
6957
      }
6958
  }
6959
    }
6960
6961
    entry = xmlExpNewNode(ctxt, type);
6962
    if (entry == NULL)
6963
        return(NULL);
6964
    entry->key = kbase;
6965
    if (type == XML_EXP_ATOM) {
6966
  entry->exp_str = name;
6967
  entry->c_max = 1;
6968
    } else if (type == XML_EXP_COUNT) {
6969
        entry->exp_min = min;
6970
        entry->exp_max = max;
6971
  entry->exp_left = left;
6972
  if ((min == 0) || (IS_NILLABLE(left)))
6973
      entry->info |= XML_EXP_NILABLE;
6974
  if (max < 0)
6975
      entry->c_max = -1;
6976
  else
6977
      entry->c_max = max * entry->exp_left->c_max;
6978
    } else {
6979
  entry->exp_left = left;
6980
  entry->exp_right = right;
6981
  if (type == XML_EXP_OR) {
6982
      if ((IS_NILLABLE(left)) || (IS_NILLABLE(right)))
6983
    entry->info |= XML_EXP_NILABLE;
6984
      if ((entry->exp_left->c_max == -1) ||
6985
          (entry->exp_right->c_max == -1))
6986
    entry->c_max = -1;
6987
      else if (entry->exp_left->c_max > entry->exp_right->c_max)
6988
          entry->c_max = entry->exp_left->c_max;
6989
      else
6990
          entry->c_max = entry->exp_right->c_max;
6991
  } else {
6992
      if ((IS_NILLABLE(left)) && (IS_NILLABLE(right)))
6993
    entry->info |= XML_EXP_NILABLE;
6994
      if ((entry->exp_left->c_max == -1) ||
6995
          (entry->exp_right->c_max == -1))
6996
    entry->c_max = -1;
6997
      else
6998
          entry->c_max = entry->exp_left->c_max + entry->exp_right->c_max;
6999
  }
7000
    }
7001
    entry->ref = 1;
7002
    if (ctxt->table[key] != NULL)
7003
        entry->next = ctxt->table[key];
7004
7005
    ctxt->table[key] = entry;
7006
    ctxt->nbElems++;
7007
7008
    return(entry);
7009
}
7010
7011
/**
7012
 * xmlExpFree:
7013
 * @ctxt: the expression context
7014
 * @exp: the expression
7015
 *
7016
 * Dereference the expression
7017
 */
7018
void
7019
xmlExpFree(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp) {
7020
    if ((exp == NULL) || (exp == forbiddenExp) || (exp == emptyExp))
7021
        return;
7022
    exp->ref--;
7023
    if (exp->ref == 0) {
7024
        unsigned short key;
7025
7026
        /* Unlink it first from the hash table */
7027
  key = exp->key % ctxt->size;
7028
  if (ctxt->table[key] == exp) {
7029
      ctxt->table[key] = exp->next;
7030
  } else {
7031
      xmlExpNodePtr tmp;
7032
7033
      tmp = ctxt->table[key];
7034
      while (tmp != NULL) {
7035
          if (tmp->next == exp) {
7036
        tmp->next = exp->next;
7037
        break;
7038
    }
7039
          tmp = tmp->next;
7040
      }
7041
  }
7042
7043
        if ((exp->type == XML_EXP_SEQ) || (exp->type == XML_EXP_OR)) {
7044
      xmlExpFree(ctxt, exp->exp_left);
7045
      xmlExpFree(ctxt, exp->exp_right);
7046
  } else if (exp->type == XML_EXP_COUNT) {
7047
      xmlExpFree(ctxt, exp->exp_left);
7048
  }
7049
        xmlFree(exp);
7050
  ctxt->nb_nodes--;
7051
    }
7052
}
7053
7054
/**
7055
 * xmlExpRef:
7056
 * @exp: the expression
7057
 *
7058
 * Increase the reference count of the expression
7059
 */
7060
void
7061
xmlExpRef(xmlExpNodePtr exp) {
7062
    if (exp != NULL)
7063
        exp->ref++;
7064
}
7065
7066
/**
7067
 * xmlExpNewAtom:
7068
 * @ctxt: the expression context
7069
 * @name: the atom name
7070
 * @len: the atom name length in byte (or -1);
7071
 *
7072
 * Get the atom associated to this name from that context
7073
 *
7074
 * Returns the node or NULL in case of error
7075
 */
7076
xmlExpNodePtr
7077
xmlExpNewAtom(xmlExpCtxtPtr ctxt, const xmlChar *name, int len) {
7078
    if ((ctxt == NULL) || (name == NULL))
7079
        return(NULL);
7080
    name = xmlDictLookup(ctxt->dict, name, len);
7081
    if (name == NULL)
7082
        return(NULL);
7083
    return(xmlExpHashGetEntry(ctxt, XML_EXP_ATOM, NULL, NULL, name, 0, 0));
7084
}
7085
7086
/**
7087
 * xmlExpNewOr:
7088
 * @ctxt: the expression context
7089
 * @left: left expression
7090
 * @right: right expression
7091
 *
7092
 * Get the atom associated to the choice @left | @right
7093
 * Note that @left and @right are consumed in the operation, to keep
7094
 * an handle on them use xmlExpRef() and use xmlExpFree() to release them,
7095
 * this is true even in case of failure (unless ctxt == NULL).
7096
 *
7097
 * Returns the node or NULL in case of error
7098
 */
7099
xmlExpNodePtr
7100
xmlExpNewOr(xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right) {
7101
    if (ctxt == NULL)
7102
        return(NULL);
7103
    if ((left == NULL) || (right == NULL)) {
7104
        xmlExpFree(ctxt, left);
7105
        xmlExpFree(ctxt, right);
7106
        return(NULL);
7107
    }
7108
    return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, left, right, NULL, 0, 0));
7109
}
7110
7111
/**
7112
 * xmlExpNewSeq:
7113
 * @ctxt: the expression context
7114
 * @left: left expression
7115
 * @right: right expression
7116
 *
7117
 * Get the atom associated to the sequence @left , @right
7118
 * Note that @left and @right are consumed in the operation, to keep
7119
 * an handle on them use xmlExpRef() and use xmlExpFree() to release them,
7120
 * this is true even in case of failure (unless ctxt == NULL).
7121
 *
7122
 * Returns the node or NULL in case of error
7123
 */
7124
xmlExpNodePtr
7125
xmlExpNewSeq(xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right) {
7126
    if (ctxt == NULL)
7127
        return(NULL);
7128
    if ((left == NULL) || (right == NULL)) {
7129
        xmlExpFree(ctxt, left);
7130
        xmlExpFree(ctxt, right);
7131
        return(NULL);
7132
    }
7133
    return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, left, right, NULL, 0, 0));
7134
}
7135
7136
/**
7137
 * xmlExpNewRange:
7138
 * @ctxt: the expression context
7139
 * @subset: the expression to be repeated
7140
 * @min: the lower bound for the repetition
7141
 * @max: the upper bound for the repetition, -1 means infinite
7142
 *
7143
 * Get the atom associated to the range (@subset){@min, @max}
7144
 * Note that @subset is consumed in the operation, to keep
7145
 * an handle on it use xmlExpRef() and use xmlExpFree() to release it,
7146
 * this is true even in case of failure (unless ctxt == NULL).
7147
 *
7148
 * Returns the node or NULL in case of error
7149
 */
7150
xmlExpNodePtr
7151
xmlExpNewRange(xmlExpCtxtPtr ctxt, xmlExpNodePtr subset, int min, int max) {
7152
    if (ctxt == NULL)
7153
        return(NULL);
7154
    if ((subset == NULL) || (min < 0) || (max < -1) ||
7155
        ((max >= 0) && (min > max))) {
7156
  xmlExpFree(ctxt, subset);
7157
        return(NULL);
7158
    }
7159
    return(xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, subset,
7160
                              NULL, NULL, min, max));
7161
}
7162
7163
/************************************************************************
7164
 *                  *
7165
 *    Public API for operations on expressions    *
7166
 *                  *
7167
 ************************************************************************/
7168
7169
static int
7170
xmlExpGetLanguageInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7171
                     const xmlChar**list, int len, int nb) {
7172
    int tmp, tmp2;
7173
tail:
7174
    switch (exp->type) {
7175
        case XML_EXP_EMPTY:
7176
      return(0);
7177
        case XML_EXP_ATOM:
7178
      for (tmp = 0;tmp < nb;tmp++)
7179
          if (list[tmp] == exp->exp_str)
7180
        return(0);
7181
            if (nb >= len)
7182
          return(-2);
7183
      list[nb] = exp->exp_str;
7184
      return(1);
7185
        case XML_EXP_COUNT:
7186
      exp = exp->exp_left;
7187
      goto tail;
7188
        case XML_EXP_SEQ:
7189
        case XML_EXP_OR:
7190
      tmp = xmlExpGetLanguageInt(ctxt, exp->exp_left, list, len, nb);
7191
      if (tmp < 0)
7192
          return(tmp);
7193
      tmp2 = xmlExpGetLanguageInt(ctxt, exp->exp_right, list, len,
7194
                                  nb + tmp);
7195
      if (tmp2 < 0)
7196
          return(tmp2);
7197
            return(tmp + tmp2);
7198
    }
7199
    return(-1);
7200
}
7201
7202
/**
7203
 * xmlExpGetLanguage:
7204
 * @ctxt: the expression context
7205
 * @exp: the expression
7206
 * @langList: where to store the tokens
7207
 * @len: the allocated length of @list
7208
 *
7209
 * Find all the strings used in @exp and store them in @list
7210
 *
7211
 * Returns the number of unique strings found, -1 in case of errors and
7212
 *         -2 if there is more than @len strings
7213
 */
7214
int
7215
xmlExpGetLanguage(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7216
                  const xmlChar**langList, int len) {
7217
    if ((ctxt == NULL) || (exp == NULL) || (langList == NULL) || (len <= 0))
7218
        return(-1);
7219
    return(xmlExpGetLanguageInt(ctxt, exp, langList, len, 0));
7220
}
7221
7222
static int
7223
xmlExpGetStartInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7224
                  const xmlChar**list, int len, int nb) {
7225
    int tmp, tmp2;
7226
tail:
7227
    switch (exp->type) {
7228
        case XML_EXP_FORBID:
7229
      return(0);
7230
        case XML_EXP_EMPTY:
7231
      return(0);
7232
        case XML_EXP_ATOM:
7233
      for (tmp = 0;tmp < nb;tmp++)
7234
          if (list[tmp] == exp->exp_str)
7235
        return(0);
7236
            if (nb >= len)
7237
          return(-2);
7238
      list[nb] = exp->exp_str;
7239
      return(1);
7240
        case XML_EXP_COUNT:
7241
      exp = exp->exp_left;
7242
      goto tail;
7243
        case XML_EXP_SEQ:
7244
      tmp = xmlExpGetStartInt(ctxt, exp->exp_left, list, len, nb);
7245
      if (tmp < 0)
7246
          return(tmp);
7247
      if (IS_NILLABLE(exp->exp_left)) {
7248
    tmp2 = xmlExpGetStartInt(ctxt, exp->exp_right, list, len,
7249
              nb + tmp);
7250
    if (tmp2 < 0)
7251
        return(tmp2);
7252
    tmp += tmp2;
7253
      }
7254
            return(tmp);
7255
        case XML_EXP_OR:
7256
      tmp = xmlExpGetStartInt(ctxt, exp->exp_left, list, len, nb);
7257
      if (tmp < 0)
7258
          return(tmp);
7259
      tmp2 = xmlExpGetStartInt(ctxt, exp->exp_right, list, len,
7260
                                  nb + tmp);
7261
      if (tmp2 < 0)
7262
          return(tmp2);
7263
            return(tmp + tmp2);
7264
    }
7265
    return(-1);
7266
}
7267
7268
/**
7269
 * xmlExpGetStart:
7270
 * @ctxt: the expression context
7271
 * @exp: the expression
7272
 * @tokList: where to store the tokens
7273
 * @len: the allocated length of @list
7274
 *
7275
 * Find all the strings that appears at the start of the languages
7276
 * accepted by @exp and store them in @list. E.g. for (a, b) | c
7277
 * it will return the list [a, c]
7278
 *
7279
 * Returns the number of unique strings found, -1 in case of errors and
7280
 *         -2 if there is more than @len strings
7281
 */
7282
int
7283
xmlExpGetStart(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7284
               const xmlChar**tokList, int len) {
7285
    if ((ctxt == NULL) || (exp == NULL) || (tokList == NULL) || (len <= 0))
7286
        return(-1);
7287
    return(xmlExpGetStartInt(ctxt, exp, tokList, len, 0));
7288
}
7289
7290
/**
7291
 * xmlExpIsNillable:
7292
 * @exp: the expression
7293
 *
7294
 * Finds if the expression is nillable, i.e. if it accepts the empty sequence
7295
 *
7296
 * Returns 1 if nillable, 0 if not and -1 in case of error
7297
 */
7298
int
7299
xmlExpIsNillable(xmlExpNodePtr exp) {
7300
    if (exp == NULL)
7301
        return(-1);
7302
    return(IS_NILLABLE(exp) != 0);
7303
}
7304
7305
static xmlExpNodePtr
7306
xmlExpStringDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar *str)
7307
{
7308
    xmlExpNodePtr ret;
7309
7310
    switch (exp->type) {
7311
  case XML_EXP_EMPTY:
7312
      return(forbiddenExp);
7313
  case XML_EXP_FORBID:
7314
      return(forbiddenExp);
7315
  case XML_EXP_ATOM:
7316
      if (exp->exp_str == str) {
7317
#ifdef DEBUG_DERIV
7318
    printf("deriv atom: equal => Empty\n");
7319
#endif
7320
          ret = emptyExp;
7321
      } else {
7322
#ifdef DEBUG_DERIV
7323
    printf("deriv atom: mismatch => forbid\n");
7324
#endif
7325
          /* TODO wildcards here */
7326
    ret = forbiddenExp;
7327
      }
7328
      return(ret);
7329
  case XML_EXP_OR: {
7330
      xmlExpNodePtr tmp;
7331
7332
#ifdef DEBUG_DERIV
7333
      printf("deriv or: => or(derivs)\n");
7334
#endif
7335
      tmp = xmlExpStringDeriveInt(ctxt, exp->exp_left, str);
7336
      if (tmp == NULL) {
7337
    return(NULL);
7338
      }
7339
      ret = xmlExpStringDeriveInt(ctxt, exp->exp_right, str);
7340
      if (ret == NULL) {
7341
          xmlExpFree(ctxt, tmp);
7342
    return(NULL);
7343
      }
7344
            ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, tmp, ret,
7345
           NULL, 0, 0);
7346
      return(ret);
7347
  }
7348
  case XML_EXP_SEQ:
7349
#ifdef DEBUG_DERIV
7350
      printf("deriv seq: starting with left\n");
7351
#endif
7352
      ret = xmlExpStringDeriveInt(ctxt, exp->exp_left, str);
7353
      if (ret == NULL) {
7354
          return(NULL);
7355
      } else if (ret == forbiddenExp) {
7356
          if (IS_NILLABLE(exp->exp_left)) {
7357
#ifdef DEBUG_DERIV
7358
        printf("deriv seq: left failed but nillable\n");
7359
#endif
7360
        ret = xmlExpStringDeriveInt(ctxt, exp->exp_right, str);
7361
    }
7362
      } else {
7363
#ifdef DEBUG_DERIV
7364
    printf("deriv seq: left match => sequence\n");
7365
#endif
7366
          exp->exp_right->ref++;
7367
          ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, exp->exp_right,
7368
                             NULL, 0, 0);
7369
      }
7370
      return(ret);
7371
  case XML_EXP_COUNT: {
7372
      int min, max;
7373
      xmlExpNodePtr tmp;
7374
7375
      if (exp->exp_max == 0)
7376
    return(forbiddenExp);
7377
      ret = xmlExpStringDeriveInt(ctxt, exp->exp_left, str);
7378
      if (ret == NULL)
7379
          return(NULL);
7380
      if (ret == forbiddenExp) {
7381
#ifdef DEBUG_DERIV
7382
    printf("deriv count: pattern mismatch => forbid\n");
7383
#endif
7384
          return(ret);
7385
      }
7386
      if (exp->exp_max == 1)
7387
    return(ret);
7388
      if (exp->exp_max < 0) /* unbounded */
7389
    max = -1;
7390
      else
7391
    max = exp->exp_max - 1;
7392
      if (exp->exp_min > 0)
7393
    min = exp->exp_min - 1;
7394
      else
7395
    min = 0;
7396
      exp->exp_left->ref++;
7397
      tmp = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left, NULL,
7398
             NULL, min, max);
7399
      if (ret == emptyExp) {
7400
#ifdef DEBUG_DERIV
7401
    printf("deriv count: match to empty => new count\n");
7402
#endif
7403
          return(tmp);
7404
      }
7405
#ifdef DEBUG_DERIV
7406
      printf("deriv count: match => sequence with new count\n");
7407
#endif
7408
      return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, tmp,
7409
                                NULL, 0, 0));
7410
  }
7411
    }
7412
    return(NULL);
7413
}
7414
7415
/**
7416
 * xmlExpStringDerive:
7417
 * @ctxt: the expression context
7418
 * @exp: the expression
7419
 * @str: the string
7420
 * @len: the string len in bytes if available
7421
 *
7422
 * Do one step of Brzozowski derivation of the expression @exp with
7423
 * respect to the input string
7424
 *
7425
 * Returns the resulting expression or NULL in case of internal error
7426
 */
7427
xmlExpNodePtr
7428
xmlExpStringDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7429
                   const xmlChar *str, int len) {
7430
    const xmlChar *input;
7431
7432
    if ((exp == NULL) || (ctxt == NULL) || (str == NULL)) {
7433
        return(NULL);
7434
    }
7435
    /*
7436
     * check the string is in the dictionary, if yes use an interned
7437
     * copy, otherwise we know it's not an acceptable input
7438
     */
7439
    input = xmlDictExists(ctxt->dict, str, len);
7440
    if (input == NULL) {
7441
        return(forbiddenExp);
7442
    }
7443
    return(xmlExpStringDeriveInt(ctxt, exp, input));
7444
}
7445
7446
static int
7447
xmlExpCheckCard(xmlExpNodePtr exp, xmlExpNodePtr sub) {
7448
    int ret = 1;
7449
7450
    if (sub->c_max == -1) {
7451
        if (exp->c_max != -1)
7452
      ret = 0;
7453
    } else if ((exp->c_max >= 0) && (exp->c_max < sub->c_max)) {
7454
        ret = 0;
7455
    }
7456
#if 0
7457
    if ((IS_NILLABLE(sub)) && (!IS_NILLABLE(exp)))
7458
        ret = 0;
7459
#endif
7460
    return(ret);
7461
}
7462
7463
static xmlExpNodePtr xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
7464
                                        xmlExpNodePtr sub);
7465
/**
7466
 * xmlExpDivide:
7467
 * @ctxt: the expressions context
7468
 * @exp: the englobing expression
7469
 * @sub: the subexpression
7470
 * @mult: the multiple expression
7471
 * @remain: the remain from the derivation of the multiple
7472
 *
7473
 * Check if exp is a multiple of sub, i.e. if there is a finite number n
7474
 * so that sub{n} subsume exp
7475
 *
7476
 * Returns the multiple value if successful, 0 if it is not a multiple
7477
 *         and -1 in case of internal error.
7478
 */
7479
7480
static int
7481
xmlExpDivide(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub,
7482
             xmlExpNodePtr *mult, xmlExpNodePtr *remain) {
7483
    int i;
7484
    xmlExpNodePtr tmp, tmp2;
7485
7486
    if (mult != NULL) *mult = NULL;
7487
    if (remain != NULL) *remain = NULL;
7488
    if (exp->c_max == -1) return(0);
7489
    if (IS_NILLABLE(exp) && (!IS_NILLABLE(sub))) return(0);
7490
7491
    for (i = 1;i <= exp->c_max;i++) {
7492
        sub->ref++;
7493
        tmp = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT,
7494
         sub, NULL, NULL, i, i);
7495
  if (tmp == NULL) {
7496
      return(-1);
7497
  }
7498
  if (!xmlExpCheckCard(tmp, exp)) {
7499
      xmlExpFree(ctxt, tmp);
7500
      continue;
7501
  }
7502
  tmp2 = xmlExpExpDeriveInt(ctxt, tmp, exp);
7503
  if (tmp2 == NULL) {
7504
      xmlExpFree(ctxt, tmp);
7505
      return(-1);
7506
  }
7507
  if ((tmp2 != forbiddenExp) && (IS_NILLABLE(tmp2))) {
7508
      if (remain != NULL)
7509
          *remain = tmp2;
7510
      else
7511
          xmlExpFree(ctxt, tmp2);
7512
      if (mult != NULL)
7513
          *mult = tmp;
7514
      else
7515
          xmlExpFree(ctxt, tmp);
7516
#ifdef DEBUG_DERIV
7517
      printf("Divide succeeded %d\n", i);
7518
#endif
7519
      return(i);
7520
  }
7521
  xmlExpFree(ctxt, tmp);
7522
  xmlExpFree(ctxt, tmp2);
7523
    }
7524
#ifdef DEBUG_DERIV
7525
    printf("Divide failed\n");
7526
#endif
7527
    return(0);
7528
}
7529
7530
/**
7531
 * xmlExpExpDeriveInt:
7532
 * @ctxt: the expressions context
7533
 * @exp: the englobing expression
7534
 * @sub: the subexpression
7535
 *
7536
 * Try to do a step of Brzozowski derivation but at a higher level
7537
 * the input being a subexpression.
7538
 *
7539
 * Returns the resulting expression or NULL in case of internal error
7540
 */
7541
static xmlExpNodePtr
7542
xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
7543
    xmlExpNodePtr ret, tmp, tmp2, tmp3;
7544
    const xmlChar **tab;
7545
    int len, i;
7546
7547
    /*
7548
     * In case of equality and if the expression can only consume a finite
7549
     * amount, then the derivation is empty
7550
     */
7551
    if ((exp == sub) && (exp->c_max >= 0)) {
7552
#ifdef DEBUG_DERIV
7553
        printf("Equal(exp, sub) and finite -> Empty\n");
7554
#endif
7555
        return(emptyExp);
7556
    }
7557
    /*
7558
     * decompose sub sequence first
7559
     */
7560
    if (sub->type == XML_EXP_EMPTY) {
7561
#ifdef DEBUG_DERIV
7562
        printf("Empty(sub) -> Empty\n");
7563
#endif
7564
  exp->ref++;
7565
        return(exp);
7566
    }
7567
    if (sub->type == XML_EXP_SEQ) {
7568
#ifdef DEBUG_DERIV
7569
        printf("Seq(sub) -> decompose\n");
7570
#endif
7571
        tmp = xmlExpExpDeriveInt(ctxt, exp, sub->exp_left);
7572
  if (tmp == NULL)
7573
      return(NULL);
7574
  if (tmp == forbiddenExp)
7575
      return(tmp);
7576
  ret = xmlExpExpDeriveInt(ctxt, tmp, sub->exp_right);
7577
  xmlExpFree(ctxt, tmp);
7578
  return(ret);
7579
    }
7580
    if (sub->type == XML_EXP_OR) {
7581
#ifdef DEBUG_DERIV
7582
        printf("Or(sub) -> decompose\n");
7583
#endif
7584
        tmp = xmlExpExpDeriveInt(ctxt, exp, sub->exp_left);
7585
  if (tmp == forbiddenExp)
7586
      return(tmp);
7587
  if (tmp == NULL)
7588
      return(NULL);
7589
  ret = xmlExpExpDeriveInt(ctxt, exp, sub->exp_right);
7590
  if ((ret == NULL) || (ret == forbiddenExp)) {
7591
      xmlExpFree(ctxt, tmp);
7592
      return(ret);
7593
  }
7594
  return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, tmp, ret, NULL, 0, 0));
7595
    }
7596
    if (!xmlExpCheckCard(exp, sub)) {
7597
#ifdef DEBUG_DERIV
7598
        printf("CheckCard(exp, sub) failed -> Forbid\n");
7599
#endif
7600
        return(forbiddenExp);
7601
    }
7602
    switch (exp->type) {
7603
        case XML_EXP_EMPTY:
7604
      if (sub == emptyExp)
7605
          return(emptyExp);
7606
#ifdef DEBUG_DERIV
7607
      printf("Empty(exp) -> Forbid\n");
7608
#endif
7609
      return(forbiddenExp);
7610
        case XML_EXP_FORBID:
7611
#ifdef DEBUG_DERIV
7612
      printf("Forbid(exp) -> Forbid\n");
7613
#endif
7614
      return(forbiddenExp);
7615
        case XML_EXP_ATOM:
7616
      if (sub->type == XML_EXP_ATOM) {
7617
          /* TODO: handle wildcards */
7618
          if (exp->exp_str == sub->exp_str) {
7619
#ifdef DEBUG_DERIV
7620
        printf("Atom match -> Empty\n");
7621
#endif
7622
        return(emptyExp);
7623
                }
7624
#ifdef DEBUG_DERIV
7625
    printf("Atom mismatch -> Forbid\n");
7626
#endif
7627
          return(forbiddenExp);
7628
      }
7629
      if ((sub->type == XML_EXP_COUNT) &&
7630
          (sub->exp_max == 1) &&
7631
          (sub->exp_left->type == XML_EXP_ATOM)) {
7632
          /* TODO: handle wildcards */
7633
          if (exp->exp_str == sub->exp_left->exp_str) {
7634
#ifdef DEBUG_DERIV
7635
        printf("Atom match -> Empty\n");
7636
#endif
7637
        return(emptyExp);
7638
    }
7639
#ifdef DEBUG_DERIV
7640
    printf("Atom mismatch -> Forbid\n");
7641
#endif
7642
          return(forbiddenExp);
7643
      }
7644
#ifdef DEBUG_DERIV
7645
      printf("Complex exp vs Atom -> Forbid\n");
7646
#endif
7647
      return(forbiddenExp);
7648
        case XML_EXP_SEQ:
7649
      /* try to get the sequence consumed only if possible */
7650
      if (xmlExpCheckCard(exp->exp_left, sub)) {
7651
    /* See if the sequence can be consumed directly */
7652
#ifdef DEBUG_DERIV
7653
    printf("Seq trying left only\n");
7654
#endif
7655
    ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub);
7656
    if ((ret != forbiddenExp) && (ret != NULL)) {
7657
#ifdef DEBUG_DERIV
7658
        printf("Seq trying left only worked\n");
7659
#endif
7660
        /*
7661
         * TODO: assumption here that we are determinist
7662
         *       i.e. we won't get to a nillable exp left
7663
         *       subset which could be matched by the right
7664
         *       part too.
7665
         * e.g.: (a | b)+,(a | c) and 'a+,a'
7666
         */
7667
        exp->exp_right->ref++;
7668
        return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret,
7669
                exp->exp_right, NULL, 0, 0));
7670
    }
7671
#ifdef DEBUG_DERIV
7672
      } else {
7673
    printf("Seq: left too short\n");
7674
#endif
7675
      }
7676
      /* Try instead to decompose */
7677
      if (sub->type == XML_EXP_COUNT) {
7678
    int min, max;
7679
7680
#ifdef DEBUG_DERIV
7681
    printf("Seq: sub is a count\n");
7682
#endif
7683
          ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub->exp_left);
7684
    if (ret == NULL)
7685
        return(NULL);
7686
    if (ret != forbiddenExp) {
7687
#ifdef DEBUG_DERIV
7688
        printf("Seq , Count match on left\n");
7689
#endif
7690
        if (sub->exp_max < 0)
7691
            max = -1;
7692
              else
7693
            max = sub->exp_max -1;
7694
        if (sub->exp_min > 0)
7695
            min = sub->exp_min -1;
7696
        else
7697
            min = 0;
7698
        exp->exp_right->ref++;
7699
        tmp = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret,
7700
                                 exp->exp_right, NULL, 0, 0);
7701
        if (tmp == NULL)
7702
            return(NULL);
7703
7704
        sub->exp_left->ref++;
7705
        tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT,
7706
              sub->exp_left, NULL, NULL, min, max);
7707
        if (tmp2 == NULL) {
7708
            xmlExpFree(ctxt, tmp);
7709
      return(NULL);
7710
        }
7711
        ret = xmlExpExpDeriveInt(ctxt, tmp, tmp2);
7712
        xmlExpFree(ctxt, tmp);
7713
        xmlExpFree(ctxt, tmp2);
7714
        return(ret);
7715
    }
7716
      }
7717
      /* we made no progress on structured operations */
7718
      break;
7719
        case XML_EXP_OR:
7720
#ifdef DEBUG_DERIV
7721
      printf("Or , trying both side\n");
7722
#endif
7723
      ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub);
7724
      if (ret == NULL)
7725
          return(NULL);
7726
      tmp = xmlExpExpDeriveInt(ctxt, exp->exp_right, sub);
7727
      if (tmp == NULL) {
7728
    xmlExpFree(ctxt, ret);
7729
          return(NULL);
7730
      }
7731
      return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, tmp, NULL, 0, 0));
7732
        case XML_EXP_COUNT: {
7733
      int min, max;
7734
7735
      if (sub->type == XML_EXP_COUNT) {
7736
          /*
7737
     * Try to see if the loop is completely subsumed
7738
     */
7739
          tmp = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub->exp_left);
7740
    if (tmp == NULL)
7741
        return(NULL);
7742
    if (tmp == forbiddenExp) {
7743
        int mult;
7744
7745
#ifdef DEBUG_DERIV
7746
        printf("Count, Count inner don't subsume\n");
7747
#endif
7748
        mult = xmlExpDivide(ctxt, sub->exp_left, exp->exp_left,
7749
                            NULL, &tmp);
7750
        if (mult <= 0) {
7751
#ifdef DEBUG_DERIV
7752
      printf("Count, Count not multiple => forbidden\n");
7753
#endif
7754
                        return(forbiddenExp);
7755
        }
7756
        if (sub->exp_max == -1) {
7757
            max = -1;
7758
      if (exp->exp_max == -1) {
7759
          if (exp->exp_min <= sub->exp_min * mult)
7760
              min = 0;
7761
          else
7762
              min = exp->exp_min - sub->exp_min * mult;
7763
      } else {
7764
#ifdef DEBUG_DERIV
7765
          printf("Count, Count finite can't subsume infinite\n");
7766
#endif
7767
                            xmlExpFree(ctxt, tmp);
7768
          return(forbiddenExp);
7769
      }
7770
        } else {
7771
      if (exp->exp_max == -1) {
7772
#ifdef DEBUG_DERIV
7773
          printf("Infinite loop consume mult finite loop\n");
7774
#endif
7775
          if (exp->exp_min > sub->exp_min * mult) {
7776
        max = -1;
7777
        min = exp->exp_min - sub->exp_min * mult;
7778
          } else {
7779
        max = -1;
7780
        min = 0;
7781
          }
7782
      } else {
7783
          if (exp->exp_max < sub->exp_max * mult) {
7784
#ifdef DEBUG_DERIV
7785
        printf("loops max mult mismatch => forbidden\n");
7786
#endif
7787
        xmlExpFree(ctxt, tmp);
7788
        return(forbiddenExp);
7789
          }
7790
          if (sub->exp_max * mult > exp->exp_min)
7791
        min = 0;
7792
          else
7793
        min = exp->exp_min - sub->exp_max * mult;
7794
          max = exp->exp_max - sub->exp_max * mult;
7795
      }
7796
        }
7797
    } else if (!IS_NILLABLE(tmp)) {
7798
        /*
7799
         * TODO: loop here to try to grow if working on finite
7800
         *       blocks.
7801
         */
7802
#ifdef DEBUG_DERIV
7803
        printf("Count, Count remain not nillable => forbidden\n");
7804
#endif
7805
        xmlExpFree(ctxt, tmp);
7806
        return(forbiddenExp);
7807
    } else if (sub->exp_max == -1) {
7808
        if (exp->exp_max == -1) {
7809
            if (exp->exp_min <= sub->exp_min) {
7810
#ifdef DEBUG_DERIV
7811
          printf("Infinite loops Okay => COUNT(0,Inf)\n");
7812
#endif
7813
                            max = -1;
7814
          min = 0;
7815
      } else {
7816
#ifdef DEBUG_DERIV
7817
          printf("Infinite loops min => Count(X,Inf)\n");
7818
#endif
7819
                            max = -1;
7820
          min = exp->exp_min - sub->exp_min;
7821
      }
7822
        } else if (exp->exp_min > sub->exp_min) {
7823
#ifdef DEBUG_DERIV
7824
      printf("loops min mismatch 1 => forbidden ???\n");
7825
#endif
7826
            xmlExpFree(ctxt, tmp);
7827
            return(forbiddenExp);
7828
        } else {
7829
      max = -1;
7830
      min = 0;
7831
        }
7832
    } else {
7833
        if (exp->exp_max == -1) {
7834
#ifdef DEBUG_DERIV
7835
      printf("Infinite loop consume finite loop\n");
7836
#endif
7837
            if (exp->exp_min > sub->exp_min) {
7838
          max = -1;
7839
          min = exp->exp_min - sub->exp_min;
7840
      } else {
7841
          max = -1;
7842
          min = 0;
7843
      }
7844
        } else {
7845
            if (exp->exp_max < sub->exp_max) {
7846
#ifdef DEBUG_DERIV
7847
          printf("loops max mismatch => forbidden\n");
7848
#endif
7849
          xmlExpFree(ctxt, tmp);
7850
          return(forbiddenExp);
7851
      }
7852
      if (sub->exp_max > exp->exp_min)
7853
          min = 0;
7854
      else
7855
          min = exp->exp_min - sub->exp_max;
7856
      max = exp->exp_max - sub->exp_max;
7857
        }
7858
    }
7859
#ifdef DEBUG_DERIV
7860
    printf("loops match => SEQ(COUNT())\n");
7861
#endif
7862
    exp->exp_left->ref++;
7863
    tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left,
7864
                              NULL, NULL, min, max);
7865
    if (tmp2 == NULL) {
7866
        return(NULL);
7867
    }
7868
                ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, tmp, tmp2,
7869
                             NULL, 0, 0);
7870
    return(ret);
7871
      }
7872
      tmp = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub);
7873
      if (tmp == NULL)
7874
    return(NULL);
7875
      if (tmp == forbiddenExp) {
7876
#ifdef DEBUG_DERIV
7877
    printf("loop mismatch => forbidden\n");
7878
#endif
7879
    return(forbiddenExp);
7880
      }
7881
      if (exp->exp_min > 0)
7882
    min = exp->exp_min - 1;
7883
      else
7884
    min = 0;
7885
      if (exp->exp_max < 0)
7886
    max = -1;
7887
      else
7888
    max = exp->exp_max - 1;
7889
7890
#ifdef DEBUG_DERIV
7891
      printf("loop match => SEQ(COUNT())\n");
7892
#endif
7893
      exp->exp_left->ref++;
7894
      tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left,
7895
              NULL, NULL, min, max);
7896
      if (tmp2 == NULL)
7897
    return(NULL);
7898
      ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, tmp, tmp2,
7899
             NULL, 0, 0);
7900
      return(ret);
7901
  }
7902
    }
7903
7904
#ifdef DEBUG_DERIV
7905
    printf("Fallback to derivative\n");
7906
#endif
7907
    if (IS_NILLABLE(sub)) {
7908
        if (!(IS_NILLABLE(exp)))
7909
      return(forbiddenExp);
7910
  else
7911
      ret = emptyExp;
7912
    } else
7913
  ret = NULL;
7914
    /*
7915
     * here the structured derivation made no progress so
7916
     * we use the default token based derivation to force one more step
7917
     */
7918
    if (ctxt->tabSize == 0)
7919
        ctxt->tabSize = 40;
7920
7921
    tab = (const xmlChar **) xmlMalloc(ctxt->tabSize *
7922
                                 sizeof(const xmlChar *));
7923
    if (tab == NULL) {
7924
  return(NULL);
7925
    }
7926
7927
    /*
7928
     * collect all the strings accepted by the subexpression on input
7929
     */
7930
    len = xmlExpGetStartInt(ctxt, sub, tab, ctxt->tabSize, 0);
7931
    while (len < 0) {
7932
        const xmlChar **temp;
7933
  temp = (const xmlChar **) xmlRealloc((xmlChar **) tab, ctxt->tabSize * 2 *
7934
                                       sizeof(const xmlChar *));
7935
  if (temp == NULL) {
7936
      xmlFree((xmlChar **) tab);
7937
      return(NULL);
7938
  }
7939
  tab = temp;
7940
  ctxt->tabSize *= 2;
7941
  len = xmlExpGetStartInt(ctxt, sub, tab, ctxt->tabSize, 0);
7942
    }
7943
    for (i = 0;i < len;i++) {
7944
        tmp = xmlExpStringDeriveInt(ctxt, exp, tab[i]);
7945
  if ((tmp == NULL) || (tmp == forbiddenExp)) {
7946
      xmlExpFree(ctxt, ret);
7947
      xmlFree((xmlChar **) tab);
7948
      return(tmp);
7949
  }
7950
  tmp2 = xmlExpStringDeriveInt(ctxt, sub, tab[i]);
7951
  if ((tmp2 == NULL) || (tmp2 == forbiddenExp)) {
7952
      xmlExpFree(ctxt, tmp);
7953
      xmlExpFree(ctxt, ret);
7954
      xmlFree((xmlChar **) tab);
7955
      return(tmp);
7956
  }
7957
  tmp3 = xmlExpExpDeriveInt(ctxt, tmp, tmp2);
7958
  xmlExpFree(ctxt, tmp);
7959
  xmlExpFree(ctxt, tmp2);
7960
7961
  if ((tmp3 == NULL) || (tmp3 == forbiddenExp)) {
7962
      xmlExpFree(ctxt, ret);
7963
      xmlFree((xmlChar **) tab);
7964
      return(tmp3);
7965
  }
7966
7967
  if (ret == NULL)
7968
      ret = tmp3;
7969
  else {
7970
      ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, tmp3, NULL, 0, 0);
7971
      if (ret == NULL) {
7972
    xmlFree((xmlChar **) tab);
7973
          return(NULL);
7974
      }
7975
  }
7976
    }
7977
    xmlFree((xmlChar **) tab);
7978
    return(ret);
7979
}
7980
7981
/**
7982
 * xmlExpExpDerive:
7983
 * @ctxt: the expressions context
7984
 * @exp: the englobing expression
7985
 * @sub: the subexpression
7986
 *
7987
 * Evaluates the expression resulting from @exp consuming a sub expression @sub
7988
 * Based on algebraic derivation and sometimes direct Brzozowski derivation
7989
 * it usually takes less than linear time and can handle expressions generating
7990
 * infinite languages.
7991
 *
7992
 * Returns the resulting expression or NULL in case of internal error, the
7993
 *         result must be freed
7994
 */
7995
xmlExpNodePtr
7996
xmlExpExpDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
7997
    if ((exp == NULL) || (ctxt == NULL) || (sub == NULL))
7998
        return(NULL);
7999
8000
    /*
8001
     * O(1) speedups
8002
     */
8003
    if (IS_NILLABLE(sub) && (!IS_NILLABLE(exp))) {
8004
#ifdef DEBUG_DERIV
8005
  printf("Sub nillable and not exp : can't subsume\n");
8006
#endif
8007
        return(forbiddenExp);
8008
    }
8009
    if (xmlExpCheckCard(exp, sub) == 0) {
8010
#ifdef DEBUG_DERIV
8011
  printf("sub generate longer sequences than exp : can't subsume\n");
8012
#endif
8013
        return(forbiddenExp);
8014
    }
8015
    return(xmlExpExpDeriveInt(ctxt, exp, sub));
8016
}
8017
8018
/**
8019
 * xmlExpSubsume:
8020
 * @ctxt: the expressions context
8021
 * @exp: the englobing expression
8022
 * @sub: the subexpression
8023
 *
8024
 * Check whether @exp accepts all the languages accepted by @sub
8025
 * the input being a subexpression.
8026
 *
8027
 * Returns 1 if true 0 if false and -1 in case of failure.
8028
 */
8029
int
8030
xmlExpSubsume(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
8031
    xmlExpNodePtr tmp;
8032
8033
    if ((exp == NULL) || (ctxt == NULL) || (sub == NULL))
8034
        return(-1);
8035
8036
    /*
8037
     * TODO: speedup by checking the language of sub is a subset of the
8038
     *       language of exp
8039
     */
8040
    /*
8041
     * O(1) speedups
8042
     */
8043
    if (IS_NILLABLE(sub) && (!IS_NILLABLE(exp))) {
8044
#ifdef DEBUG_DERIV
8045
  printf("Sub nillable and not exp : can't subsume\n");
8046
#endif
8047
        return(0);
8048
    }
8049
    if (xmlExpCheckCard(exp, sub) == 0) {
8050
#ifdef DEBUG_DERIV
8051
  printf("sub generate longer sequences than exp : can't subsume\n");
8052
#endif
8053
        return(0);
8054
    }
8055
    tmp = xmlExpExpDeriveInt(ctxt, exp, sub);
8056
#ifdef DEBUG_DERIV
8057
    printf("Result derivation :\n");
8058
    PRINT_EXP(tmp);
8059
#endif
8060
    if (tmp == NULL)
8061
        return(-1);
8062
    if (tmp == forbiddenExp)
8063
  return(0);
8064
    if (tmp == emptyExp)
8065
  return(1);
8066
    if ((tmp != NULL) && (IS_NILLABLE(tmp))) {
8067
        xmlExpFree(ctxt, tmp);
8068
        return(1);
8069
    }
8070
    xmlExpFree(ctxt, tmp);
8071
    return(0);
8072
}
8073
8074
/************************************************************************
8075
 *                  *
8076
 *      Parsing expression        *
8077
 *                  *
8078
 ************************************************************************/
8079
8080
static xmlExpNodePtr xmlExpParseExpr(xmlExpCtxtPtr ctxt);
8081
8082
#undef CUR
8083
#define CUR (*ctxt->cur)
8084
#undef NEXT
8085
#define NEXT ctxt->cur++;
8086
#undef IS_BLANK
8087
#define IS_BLANK(c) ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t'))
8088
#define SKIP_BLANKS while (IS_BLANK(*ctxt->cur)) ctxt->cur++;
8089
8090
static int
8091
xmlExpParseNumber(xmlExpCtxtPtr ctxt) {
8092
    int ret = 0;
8093
8094
    SKIP_BLANKS
8095
    if (CUR == '*') {
8096
  NEXT
8097
  return(-1);
8098
    }
8099
    if ((CUR < '0') || (CUR > '9'))
8100
        return(-1);
8101
    while ((CUR >= '0') && (CUR <= '9')) {
8102
        ret = ret * 10 + (CUR - '0');
8103
  NEXT
8104
    }
8105
    return(ret);
8106
}
8107
8108
static xmlExpNodePtr
8109
xmlExpParseOr(xmlExpCtxtPtr ctxt) {
8110
    const char *base;
8111
    xmlExpNodePtr ret;
8112
    const xmlChar *val;
8113
8114
    SKIP_BLANKS
8115
    base = ctxt->cur;
8116
    if (*ctxt->cur == '(') {
8117
        NEXT
8118
  ret = xmlExpParseExpr(ctxt);
8119
  SKIP_BLANKS
8120
  if (*ctxt->cur != ')') {
8121
      fprintf(stderr, "unbalanced '(' : %s\n", base);
8122
      xmlExpFree(ctxt, ret);
8123
      return(NULL);
8124
  }
8125
  NEXT;
8126
  SKIP_BLANKS
8127
  goto parse_quantifier;
8128
    }
8129
    while ((CUR != 0) && (!(IS_BLANK(CUR))) && (CUR != '(') &&
8130
           (CUR != ')') && (CUR != '|') && (CUR != ',') && (CUR != '{') &&
8131
     (CUR != '*') && (CUR != '+') && (CUR != '?') && (CUR != '}'))
8132
  NEXT;
8133
    val = xmlDictLookup(ctxt->dict, BAD_CAST base, ctxt->cur - base);
8134
    if (val == NULL)
8135
        return(NULL);
8136
    ret = xmlExpHashGetEntry(ctxt, XML_EXP_ATOM, NULL, NULL, val, 0, 0);
8137
    if (ret == NULL)
8138
        return(NULL);
8139
    SKIP_BLANKS
8140
parse_quantifier:
8141
    if (CUR == '{') {
8142
        int min, max;
8143
8144
        NEXT
8145
  min = xmlExpParseNumber(ctxt);
8146
  if (min < 0) {
8147
      xmlExpFree(ctxt, ret);
8148
      return(NULL);
8149
  }
8150
  SKIP_BLANKS
8151
  if (CUR == ',') {
8152
      NEXT
8153
      max = xmlExpParseNumber(ctxt);
8154
      SKIP_BLANKS
8155
  } else
8156
      max = min;
8157
  if (CUR != '}') {
8158
      xmlExpFree(ctxt, ret);
8159
      return(NULL);
8160
  }
8161
        NEXT
8162
  ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
8163
                           min, max);
8164
  SKIP_BLANKS
8165
    } else if (CUR == '?') {
8166
        NEXT
8167
  ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
8168
                           0, 1);
8169
  SKIP_BLANKS
8170
    } else if (CUR == '+') {
8171
        NEXT
8172
  ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
8173
                           1, -1);
8174
  SKIP_BLANKS
8175
    } else if (CUR == '*') {
8176
        NEXT
8177
  ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL,
8178
                           0, -1);
8179
  SKIP_BLANKS
8180
    }
8181
    return(ret);
8182
}
8183
8184
8185
static xmlExpNodePtr
8186
xmlExpParseSeq(xmlExpCtxtPtr ctxt) {
8187
    xmlExpNodePtr ret, right;
8188
8189
    ret = xmlExpParseOr(ctxt);
8190
    SKIP_BLANKS
8191
    while (CUR == '|') {
8192
        NEXT
8193
  right = xmlExpParseOr(ctxt);
8194
  if (right == NULL) {
8195
      xmlExpFree(ctxt, ret);
8196
      return(NULL);
8197
  }
8198
  ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, right, NULL, 0, 0);
8199
  if (ret == NULL)
8200
      return(NULL);
8201
    }
8202
    return(ret);
8203
}
8204
8205
static xmlExpNodePtr
8206
xmlExpParseExpr(xmlExpCtxtPtr ctxt) {
8207
    xmlExpNodePtr ret, right;
8208
8209
    ret = xmlExpParseSeq(ctxt);
8210
    SKIP_BLANKS
8211
    while (CUR == ',') {
8212
        NEXT
8213
  right = xmlExpParseSeq(ctxt);
8214
  if (right == NULL) {
8215
      xmlExpFree(ctxt, ret);
8216
      return(NULL);
8217
  }
8218
  ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, right, NULL, 0, 0);
8219
  if (ret == NULL)
8220
      return(NULL);
8221
    }
8222
    return(ret);
8223
}
8224
8225
/**
8226
 * xmlExpParse:
8227
 * @ctxt: the expressions context
8228
 * @expr: the 0 terminated string
8229
 *
8230
 * Minimal parser for regexps, it understand the following constructs
8231
 *  - string terminals
8232
 *  - choice operator |
8233
 *  - sequence operator ,
8234
 *  - subexpressions (...)
8235
 *  - usual cardinality operators + * and ?
8236
 *  - finite sequences  { min, max }
8237
 *  - infinite sequences { min, * }
8238
 * There is minimal checkings made especially no checking on strings values
8239
 *
8240
 * Returns a new expression or NULL in case of failure
8241
 */
8242
xmlExpNodePtr
8243
xmlExpParse(xmlExpCtxtPtr ctxt, const char *expr) {
8244
    xmlExpNodePtr ret;
8245
8246
    ctxt->expr = expr;
8247
    ctxt->cur = expr;
8248
8249
    ret = xmlExpParseExpr(ctxt);
8250
    SKIP_BLANKS
8251
    if (*ctxt->cur != 0) {
8252
        xmlExpFree(ctxt, ret);
8253
        return(NULL);
8254
    }
8255
    return(ret);
8256
}
8257
8258
static void
8259
xmlExpDumpInt(xmlBufferPtr buf, xmlExpNodePtr expr, int glob) {
8260
    xmlExpNodePtr c;
8261
8262
    if (expr == NULL) return;
8263
    if (glob) xmlBufferWriteChar(buf, "(");
8264
    switch (expr->type) {
8265
        case XML_EXP_EMPTY:
8266
      xmlBufferWriteChar(buf, "empty");
8267
      break;
8268
        case XML_EXP_FORBID:
8269
      xmlBufferWriteChar(buf, "forbidden");
8270
      break;
8271
        case XML_EXP_ATOM:
8272
      xmlBufferWriteCHAR(buf, expr->exp_str);
8273
      break;
8274
        case XML_EXP_SEQ:
8275
      c = expr->exp_left;
8276
      if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
8277
          xmlExpDumpInt(buf, c, 1);
8278
      else
8279
          xmlExpDumpInt(buf, c, 0);
8280
      xmlBufferWriteChar(buf, " , ");
8281
      c = expr->exp_right;
8282
      if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
8283
          xmlExpDumpInt(buf, c, 1);
8284
      else
8285
          xmlExpDumpInt(buf, c, 0);
8286
            break;
8287
        case XML_EXP_OR:
8288
      c = expr->exp_left;
8289
      if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
8290
          xmlExpDumpInt(buf, c, 1);
8291
      else
8292
          xmlExpDumpInt(buf, c, 0);
8293
      xmlBufferWriteChar(buf, " | ");
8294
      c = expr->exp_right;
8295
      if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
8296
          xmlExpDumpInt(buf, c, 1);
8297
      else
8298
          xmlExpDumpInt(buf, c, 0);
8299
            break;
8300
        case XML_EXP_COUNT: {
8301
      char rep[40];
8302
8303
      c = expr->exp_left;
8304
      if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR))
8305
          xmlExpDumpInt(buf, c, 1);
8306
      else
8307
          xmlExpDumpInt(buf, c, 0);
8308
      if ((expr->exp_min == 0) && (expr->exp_max == 1)) {
8309
    rep[0] = '?';
8310
    rep[1] = 0;
8311
      } else if ((expr->exp_min == 0) && (expr->exp_max == -1)) {
8312
    rep[0] = '*';
8313
    rep[1] = 0;
8314
      } else if ((expr->exp_min == 1) && (expr->exp_max == -1)) {
8315
    rep[0] = '+';
8316
    rep[1] = 0;
8317
      } else if (expr->exp_max == expr->exp_min) {
8318
          snprintf(rep, 39, "{%d}", expr->exp_min);
8319
      } else if (expr->exp_max < 0) {
8320
          snprintf(rep, 39, "{%d,inf}", expr->exp_min);
8321
      } else {
8322
          snprintf(rep, 39, "{%d,%d}", expr->exp_min, expr->exp_max);
8323
      }
8324
      rep[39] = 0;
8325
      xmlBufferWriteChar(buf, rep);
8326
      break;
8327
  }
8328
  default:
8329
      fprintf(stderr, "Error in tree\n");
8330
    }
8331
    if (glob)
8332
        xmlBufferWriteChar(buf, ")");
8333
}
8334
/**
8335
 * xmlExpDump:
8336
 * @buf:  a buffer to receive the output
8337
 * @expr:  the compiled expression
8338
 *
8339
 * Serialize the expression as compiled to the buffer
8340
 */
8341
void
8342
xmlExpDump(xmlBufferPtr buf, xmlExpNodePtr expr) {
8343
    if ((buf == NULL) || (expr == NULL))
8344
        return;
8345
    xmlExpDumpInt(buf, expr, 0);
8346
}
8347
8348
/**
8349
 * xmlExpMaxToken:
8350
 * @expr: a compiled expression
8351
 *
8352
 * Indicate the maximum number of input a expression can accept
8353
 *
8354
 * Returns the maximum length or -1 in case of error
8355
 */
8356
int
8357
xmlExpMaxToken(xmlExpNodePtr expr) {
8358
    if (expr == NULL)
8359
        return(-1);
8360
    return(expr->c_max);
8361
}
8362
8363
/**
8364
 * xmlExpCtxtNbNodes:
8365
 * @ctxt: an expression context
8366
 *
8367
 * Debugging facility provides the number of allocated nodes at a that point
8368
 *
8369
 * Returns the number of nodes in use or -1 in case of error
8370
 */
8371
int
8372
xmlExpCtxtNbNodes(xmlExpCtxtPtr ctxt) {
8373
    if (ctxt == NULL)
8374
        return(-1);
8375
    return(ctxt->nb_nodes);
8376
}
8377
8378
/**
8379
 * xmlExpCtxtNbCons:
8380
 * @ctxt: an expression context
8381
 *
8382
 * Debugging facility provides the number of allocated nodes over lifetime
8383
 *
8384
 * Returns the number of nodes ever allocated or -1 in case of error
8385
 */
8386
int
8387
xmlExpCtxtNbCons(xmlExpCtxtPtr ctxt) {
8388
    if (ctxt == NULL)
8389
        return(-1);
8390
    return(ctxt->nb_cons);
8391
}
8392
8393
#endif /* LIBXML_EXPR_ENABLED */
8394
8395
#endif /* LIBXML_REGEXP_ENABLED */