Coverage Report

Created: 2025-07-07 10:01

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