]> granicus.if.org Git - postgresql/blob - src/include/regex/regguts.h
Remove useless "retry memory" logic within regex engine.
[postgresql] / src / include / regex / regguts.h
1 /*
2  * Internal interface definitions, etc., for the reg package
3  *
4  * Copyright (c) 1998, 1999 Henry Spencer.      All rights reserved.
5  *
6  * Development of this software was funded, in part, by Cray Research Inc.,
7  * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics
8  * Corporation, none of whom are responsible for the results.  The author
9  * thanks all of them.
10  *
11  * Redistribution and use in source and binary forms -- with or without
12  * modification -- are permitted for any purpose, provided that
13  * redistributions in source form retain this entire copyright notice and
14  * indicate the origin and nature of any modifications.
15  *
16  * I'd appreciate being given credit for this package in the documentation
17  * of software which uses it, but that is not a requirement.
18  *
19  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
20  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
21  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
22  * HENRY SPENCER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * src/include/regex/regguts.h
31  */
32
33
34
35 /*
36  * Environmental customization.  It should not (I hope) be necessary to
37  * alter the file you are now reading -- regcustom.h should handle it all,
38  * given care here and elsewhere.
39  */
40 #include "regcustom.h"
41
42
43
44 /*
45  * Things that regcustom.h might override.
46  */
47
48 /* assertions */
49 #ifndef assert
50 #ifndef REG_DEBUG
51 #define  NDEBUG                                 /* no assertions */
52 #endif
53 #include <assert.h>
54 #endif
55
56 /* voids */
57 #ifndef DISCARD
58 #define DISCARD void                    /* for throwing values away */
59 #endif
60 #ifndef VS
61 #define VS(x)   ((void *)(x))   /* cast something to generic ptr */
62 #endif
63
64 /* function-pointer declarator */
65 #ifndef FUNCPTR
66 #define FUNCPTR(name, args) (*(name)) args
67 #endif
68
69 /* memory allocation */
70 #ifndef MALLOC
71 #define MALLOC(n)       malloc(n)
72 #endif
73 #ifndef REALLOC
74 #define REALLOC(p, n)   realloc(VS(p), n)
75 #endif
76 #ifndef FREE
77 #define FREE(p)         free(VS(p))
78 #endif
79
80 /* want size of a char in bits, and max value in bounded quantifiers */
81 #ifndef CHAR_BIT
82 #include <limits.h>
83 #endif
84 #ifndef _POSIX2_RE_DUP_MAX
85 #define _POSIX2_RE_DUP_MAX      255 /* normally from <limits.h> */
86 #endif
87
88
89
90 /*
91  * misc
92  */
93
94 #define NOTREACHED      0
95 #define xxx             1
96
97 #define DUPMAX  _POSIX2_RE_DUP_MAX
98 #define INFINITY        (DUPMAX+1)
99
100 #define REMAGIC 0xfed7                  /* magic number for main struct */
101
102
103
104 /*
105  * debugging facilities
106  */
107 #ifdef REG_DEBUG
108 /* FDEBUG does finite-state tracing */
109 #define FDEBUG(arglist) { if (v->eflags&REG_FTRACE) printf arglist; }
110 /* MDEBUG does higher-level tracing */
111 #define MDEBUG(arglist) { if (v->eflags&REG_MTRACE) printf arglist; }
112 #else
113 #define FDEBUG(arglist) {}
114 #define MDEBUG(arglist) {}
115 #endif
116
117
118
119 /*
120  * bitmap manipulation
121  */
122 #define UBITS   (CHAR_BIT * sizeof(unsigned))
123 #define BSET(uv, sn)    ((uv)[(sn)/UBITS] |= (unsigned)1 << ((sn)%UBITS))
124 #define ISBSET(uv, sn)  ((uv)[(sn)/UBITS] & ((unsigned)1 << ((sn)%UBITS)))
125
126
127
128 /*
129  * We dissect a chr into byts for colormap table indexing.      Here we define
130  * a byt, which will be the same as a byte on most machines...  The exact
131  * size of a byt is not critical, but about 8 bits is good, and extraction
132  * of 8-bit chunks is sometimes especially fast.
133  */
134 #ifndef BYTBITS
135 #define BYTBITS 8                               /* bits in a byt */
136 #endif
137 #define BYTTAB  (1<<BYTBITS)    /* size of table with one entry per byt value */
138 #define BYTMASK (BYTTAB-1)              /* bit mask for byt */
139 #define NBYTS   ((CHRBITS+BYTBITS-1)/BYTBITS)
140 /* the definition of GETCOLOR(), below, assumes NBYTS <= 4 */
141
142
143
144 /*
145  * As soon as possible, we map chrs into equivalence classes -- "colors" --
146  * which are of much more manageable number.
147  */
148 typedef short color;                    /* colors of characters */
149 typedef int pcolor;                             /* what color promotes to */
150
151 #define COLORLESS       (-1)            /* impossible color */
152 #define WHITE           0                       /* default color, parent of all others */
153
154
155
156 /*
157  * A colormap is a tree -- more precisely, a DAG -- indexed at each level
158  * by a byt of the chr, to map the chr to a color efficiently.  Because
159  * lower sections of the tree can be shared, it can exploit the usual
160  * sparseness of such a mapping table.  The tree is always NBYTS levels
161  * deep (in the past it was shallower during construction but was "filled"
162  * to full depth at the end of that); areas that are unaltered as yet point
163  * to "fill blocks" which are entirely WHITE in color.
164  */
165
166 /* the tree itself */
167 struct colors
168 {
169         color           ccolor[BYTTAB];
170 };
171 struct ptrs
172 {
173         union tree *pptr[BYTTAB];
174 };
175 union tree
176 {
177         struct colors colors;
178         struct ptrs ptrs;
179 };
180
181 #define tcolor  colors.ccolor
182 #define tptr    ptrs.pptr
183
184 /*
185  * Per-color data structure for the compile-time color machinery
186  *
187  * If "sub" is not NOSUB then it is the number of the color's current
188  * subcolor, i.e. we are in process of dividing this color (character
189  * equivalence class) into two colors.  See src/backend/regex/README for
190  * discussion of subcolors.
191  *
192  * Currently-unused colors have the FREECOL bit set and are linked into a
193  * freelist using their "sub" fields, but only if their color numbers are
194  * less than colormap.max.  Any array entries beyond "max" are just garbage.
195  */
196 struct colordesc
197 {
198         uchr            nchrs;                  /* number of chars of this color */
199         color           sub;                    /* open subcolor, if any; or free-chain ptr */
200 #define  NOSUB   COLORLESS              /* value of "sub" when no open subcolor */
201         struct arc *arcs;                       /* chain of all arcs of this color */
202         int                     flags;                  /* bit values defined next */
203 #define  FREECOL 01                             /* currently free */
204 #define  PSEUDO  02                             /* pseudocolor, no real chars */
205 #define  UNUSEDCOLOR(cd) ((cd)->flags&FREECOL)
206         union tree *block;                      /* block of solid color, if any */
207 };
208
209 /*
210  * The color map itself
211  *
212  * Only the "tree" part is used at execution time, and that only via the
213  * GETCOLOR() macro.  Possibly that should be separated from the compile-time
214  * data.
215  */
216 struct colormap
217 {
218         int                     magic;
219 #define  CMMAGIC 0x876
220         struct vars *v;                         /* for compile error reporting */
221         size_t          ncds;                   /* allocated length of colordescs array */
222         size_t          max;                    /* highest color number currently in use */
223         color           free;                   /* beginning of free chain (if non-0) */
224         struct colordesc *cd;           /* pointer to array of colordescs */
225 #define  CDEND(cm)       (&(cm)->cd[(cm)->max + 1])
226         /* If we need up to NINLINECDS, we store them here to save a malloc */
227 #define  NINLINECDS  ((size_t)10)
228         struct colordesc cdspace[NINLINECDS];
229         union tree      tree[NBYTS];    /* tree top, plus lower-level fill blocks */
230 };
231
232 /* optimization magic to do fast chr->color mapping */
233 #define B0(c)   ((c) & BYTMASK)
234 #define B1(c)   (((c)>>BYTBITS) & BYTMASK)
235 #define B2(c)   (((c)>>(2*BYTBITS)) & BYTMASK)
236 #define B3(c)   (((c)>>(3*BYTBITS)) & BYTMASK)
237 #if NBYTS == 1
238 #define GETCOLOR(cm, c) ((cm)->tree->tcolor[B0(c)])
239 #endif
240 /* beware, for NBYTS>1, GETCOLOR() is unsafe -- 2nd arg used repeatedly */
241 #if NBYTS == 2
242 #define GETCOLOR(cm, c) ((cm)->tree->tptr[B1(c)]->tcolor[B0(c)])
243 #endif
244 #if NBYTS == 4
245 #define GETCOLOR(cm, c) ((cm)->tree->tptr[B3(c)]->tptr[B2(c)]->tptr[B1(c)]->tcolor[B0(c)])
246 #endif
247
248
249 /*
250  * Interface definitions for locale-interface functions in regc_locale.c.
251  */
252
253 /*
254  * Representation of a set of characters.  chrs[] represents individual
255  * code points, ranges[] represents ranges in the form min..max inclusive.
256  *
257  * Note that in cvecs gotten from newcvec() and intended to be freed by
258  * freecvec(), both arrays of chrs are after the end of the struct, not
259  * separately malloc'd; so chrspace and rangespace are effectively immutable.
260  */
261 struct cvec
262 {
263         int                     nchrs;                  /* number of chrs */
264         int                     chrspace;               /* number of chrs allocated in chrs[] */
265         chr                *chrs;                       /* pointer to vector of chrs */
266         int                     nranges;                /* number of ranges (chr pairs) */
267         int                     rangespace;             /* number of ranges allocated in ranges[] */
268         chr                *ranges;                     /* pointer to vector of chr pairs */
269 };
270
271
272 /*
273  * definitions for NFA internal representation
274  *
275  * Having a "from" pointer within each arc may seem redundant, but it
276  * saves a lot of hassle.
277  */
278 struct state;
279
280 struct arc
281 {
282         int                     type;
283 #define  ARCFREE '\0'
284         color           co;
285         struct state *from;                     /* where it's from (and contained within) */
286         struct state *to;                       /* where it's to */
287         struct arc *outchain;           /* *from's outs chain or free chain */
288 #define  freechain       outchain
289         struct arc *inchain;            /* *to's ins chain */
290         struct arc *colorchain;         /* color's arc chain */
291         struct arc *colorchainRev;      /* back-link in color's arc chain */
292 };
293
294 struct arcbatch
295 {                                                               /* for bulk allocation of arcs */
296         struct arcbatch *next;
297 #define  ABSIZE  10
298         struct arc      a[ABSIZE];
299 };
300
301 struct state
302 {
303         int                     no;
304 #define  FREESTATE       (-1)
305         char            flag;                   /* marks special states */
306         int                     nins;                   /* number of inarcs */
307         struct arc *ins;                        /* chain of inarcs */
308         int                     nouts;                  /* number of outarcs */
309         struct arc *outs;                       /* chain of outarcs */
310         struct arc *free;                       /* chain of free arcs */
311         struct state *tmp;                      /* temporary for traversal algorithms */
312         struct state *next;                     /* chain for traversing all */
313         struct state *prev;                     /* back chain */
314         struct arcbatch oas;            /* first arcbatch, avoid malloc in easy case */
315         int                     noas;                   /* number of arcs used in first arcbatch */
316 };
317
318 struct nfa
319 {
320         struct state *pre;                      /* pre-initial state */
321         struct state *init;                     /* initial state */
322         struct state *final;            /* final state */
323         struct state *post;                     /* post-final state */
324         int                     nstates;                /* for numbering states */
325         struct state *states;           /* state-chain header */
326         struct state *slast;            /* tail of the chain */
327         struct state *free;                     /* free list */
328         struct colormap *cm;            /* the color map */
329         color           bos[2];                 /* colors, if any, assigned to BOS and BOL */
330         color           eos[2];                 /* colors, if any, assigned to EOS and EOL */
331         size_t          size;                   /* Current NFA size; differs from nstates as
332                                                                  * it also counts the number of states created
333                                                                  * by children of this state. */
334         struct vars *v;                         /* simplifies compile error reporting */
335         struct nfa *parent;                     /* parent NFA, if any */
336 };
337
338
339
340 /*
341  * definitions for compacted NFA
342  */
343 struct carc
344 {
345         color           co;                             /* COLORLESS is list terminator */
346         int                     to;                             /* state number */
347 };
348
349 struct cnfa
350 {
351         int                     nstates;                /* number of states */
352         int                     ncolors;                /* number of colors */
353         int                     flags;
354 #define  HASLACONS       01                     /* uses lookahead constraints */
355         int                     pre;                    /* setup state number */
356         int                     post;                   /* teardown state number */
357         color           bos[2];                 /* colors, if any, assigned to BOS and BOL */
358         color           eos[2];                 /* colors, if any, assigned to EOS and EOL */
359         struct carc **states;           /* vector of pointers to outarc lists */
360         struct carc *arcs;                      /* the area for the lists */
361 };
362
363 #define ZAPCNFA(cnfa)   ((cnfa).nstates = 0)
364 #define NULLCNFA(cnfa)  ((cnfa).nstates == 0)
365
366 /*
367  * Used to limit the maximum NFA size to something sane. [Tcl Bug 1810264]
368  */
369 #ifndef REG_MAX_STATES
370 #define REG_MAX_STATES  100000
371 #endif
372
373 /*
374  * subexpression tree
375  *
376  * "op" is one of:
377  *              '='  plain regex without interesting substructure (implemented as DFA)
378  *              'b'  back-reference (has no substructure either)
379  *              '('  capture node: captures the match of its single child
380  *              '.'  concatenation: matches a match for left, then a match for right
381  *              '|'  alternation: matches a match for left or a match for right
382  *              '*'  iteration: matches some number of matches of its single child
383  *
384  * Note: the right child of an alternation must be another alternation or
385  * NULL; hence, an N-way branch requires N alternation nodes, not N-1 as you
386  * might expect.  This could stand to be changed.  Actually I'd rather see
387  * a single alternation node with N children, but that will take revising
388  * the representation of struct subre.
389  *
390  * Note: when a backref is directly quantified, we stick the min/max counts
391  * into the backref rather than plastering an iteration node on top.  This is
392  * for efficiency: there is no need to search for possible division points.
393  */
394 struct subre
395 {
396         char            op;                             /* see type codes above */
397         char            flags;
398 #define  LONGER  01                             /* prefers longer match */
399 #define  SHORTER 02                             /* prefers shorter match */
400 #define  MIXED   04                             /* mixed preference below */
401 #define  CAP 010                                /* capturing parens below */
402 #define  BACKR   020                    /* back reference below */
403 #define  INUSE   0100                   /* in use in final tree */
404 #define  LOCAL   03                             /* bits which may not propagate up */
405 #define  LMIX(f) ((f)<<2)               /* LONGER -> MIXED */
406 #define  SMIX(f) ((f)<<1)               /* SHORTER -> MIXED */
407 #define  UP(f)   (((f)&~LOCAL) | (LMIX(f) & SMIX(f) & MIXED))
408 #define  MESSY(f)        ((f)&(MIXED|CAP|BACKR))
409 #define  PREF(f) ((f)&LOCAL)
410 #define  PREF2(f1, f2)   ((PREF(f1) != 0) ? PREF(f1) : PREF(f2))
411 #define  COMBINE(f1, f2) (UP((f1)|(f2)) | PREF2(f1, f2))
412         short           id;                             /* ID of subre (1..ntree) */
413         int                     subno;                  /* subexpression number (for 'b' and '(') */
414         short           min;                    /* min repetitions for iteration or backref */
415         short           max;                    /* max repetitions for iteration or backref */
416         struct subre *left;                     /* left child, if any (also freelist chain) */
417         struct subre *right;            /* right child, if any */
418         struct state *begin;            /* outarcs from here... */
419         struct state *end;                      /* ...ending in inarcs here */
420         struct cnfa cnfa;                       /* compacted NFA, if any */
421         struct subre *chain;            /* for bookkeeping and error cleanup */
422 };
423
424
425
426 /*
427  * table of function pointers for generic manipulation functions
428  * A regex_t's re_fns points to one of these.
429  */
430 struct fns
431 {
432         void            FUNCPTR(free, (regex_t *));
433 };
434
435
436
437 /*
438  * the insides of a regex_t, hidden behind a void *
439  */
440 struct guts
441 {
442         int                     magic;
443 #define  GUTSMAGIC       0xfed9
444         int                     cflags;                 /* copy of compile flags */
445         long            info;                   /* copy of re_info */
446         size_t          nsub;                   /* copy of re_nsub */
447         struct subre *tree;
448         struct cnfa search;                     /* for fast preliminary search */
449         int                     ntree;
450         struct colormap cmap;
451         int                     FUNCPTR(compare, (const chr *, const chr *, size_t));
452         struct subre *lacons;           /* lookahead-constraint vector */
453         int                     nlacons;                /* size of lacons */
454 };