Coverage Report

Created: 2025-08-04 07:15

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