Merge from vendor branch GDB:
[dragonfly.git] / lib / libc / regex / regcomp.c
1 /*-
2  * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3  * Copyright (c) 1992, 1993, 1994
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Henry Spencer.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      @(#)regcomp.c   8.5 (Berkeley) 3/20/94
38  *
39  * $FreeBSD: src/lib/libc/regex/regcomp.c,v 1.13.2.2 2002/03/20 13:13:15 dcs Exp $
40  * $DragonFly: src/lib/libc/regex/regcomp.c,v 1.5 2004/10/25 19:38:01 drhodus Exp $
41  *
42  * @(#)regcomp.c        8.5 (Berkeley) 3/20/94
43  */
44
45 #include <sys/types.h>
46 #include <stdio.h>
47 #include <string.h>
48 #include <ctype.h>
49 #include <limits.h>
50 #include <stdlib.h>
51 #include <regex.h>
52
53 #include "collate.h"
54
55 #include "utils.h"
56 #include "regex2.h"
57
58 #include "cclass.h"
59 #include "cname.h"
60
61 /*
62  * parse structure, passed up and down to avoid global variables and
63  * other clumsinesses
64  */
65 struct parse {
66         char *next;             /* next character in RE */
67         char *end;              /* end of string (-> NUL normally) */
68         int error;              /* has an error been seen? */
69         sop *strip;             /* malloced strip */
70         sopno ssize;            /* malloced strip size (allocated) */
71         sopno slen;             /* malloced strip length (used) */
72         int ncsalloc;           /* number of csets allocated */
73         struct re_guts *g;
74 #       define  NPAREN  10      /* we need to remember () 1-9 for back refs */
75         sopno pbegin[NPAREN];   /* -> ( ([0] unused) */
76         sopno pend[NPAREN];     /* -> ) ([0] unused) */
77 };
78
79 /* ========= begin header generated by ./mkh ========= */
80 #ifdef __cplusplus
81 extern "C" {
82 #endif
83
84 /* === regcomp.c === */
85 static void p_ere(struct parse *p, int stop);
86 static void p_ere_exp(struct parse *p);
87 static void p_str(struct parse *p);
88 static void p_bre(struct parse *p, int end1, int end2);
89 static int p_simp_re(struct parse *p, int starordinary);
90 static int p_count(struct parse *p);
91 static void p_bracket(struct parse *p);
92 static void p_b_term(struct parse *p, cset *cs);
93 static void p_b_cclass(struct parse *p, cset *cs);
94 static void p_b_eclass(struct parse *p, cset *cs);
95 static char p_b_symbol(struct parse *p);
96 static char p_b_coll_elem(struct parse *p, int endc);
97 static char othercase(int ch);
98 static void bothcases(struct parse *p, int ch);
99 static void ordinary(struct parse *p, int ch);
100 static void nonnewline(struct parse *p);
101 static void repeat(struct parse *p, sopno start, int from, int to);
102 static int seterr(struct parse *p, int e);
103 static cset *allocset(struct parse *p);
104 static void freeset(struct parse *p, cset *cs);
105 static int freezeset(struct parse *p, cset *cs);
106 static int firstch(struct parse *p, cset *cs);
107 static int nch(struct parse *p, cset *cs);
108 static void mcadd(struct parse *p, cset *cs, char *cp);
109 #if used
110 static void mcsub(cset *cs, char *cp);
111 static int mcin(cset *cs, char *cp);
112 static char *mcfind(cset *cs, char *cp);
113 #endif
114 static void mcinvert(struct parse *p, cset *cs);
115 static void mccase(struct parse *p, cset *cs);
116 static int isinsets(struct re_guts *g, int c);
117 static int samesets(struct re_guts *g, int c1, int c2);
118 static void categorize(struct parse *p, struct re_guts *g);
119 static sopno dupl(struct parse *p, sopno start, sopno finish);
120 static void doemit(struct parse *p, sop op, size_t opnd);
121 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
122 static void dofwd(struct parse *p, sopno pos, sop value);
123 static void enlarge(struct parse *p, sopno size);
124 static void stripsnug(struct parse *p, struct re_guts *g);
125 static void findmust(struct parse *p, struct re_guts *g);
126 static int altoffset(sop *scan, int offset, int mccs);
127 static void computejumps(struct parse *p, struct re_guts *g);
128 static void computematchjumps(struct parse *p, struct re_guts *g);
129 static sopno pluscount(struct parse *p, struct re_guts *g);
130
131 #ifdef __cplusplus
132 }
133 #endif
134 /* ========= end header generated by ./mkh ========= */
135
136 static char nuls[10];           /* place to point scanner in event of error */
137
138 /*
139  * macros for use with parse structure
140  * BEWARE:  these know that the parse structure is named `p' !!!
141  */
142 #define PEEK()  (*p->next)
143 #define PEEK2() (*(p->next+1))
144 #define MORE()  (p->next < p->end)
145 #define MORE2() (p->next+1 < p->end)
146 #define SEE(c)  (MORE() && PEEK() == (c))
147 #define SEETWO(a, b)    (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
148 #define EAT(c)  ((SEE(c)) ? (NEXT(), 1) : 0)
149 #define EATTWO(a, b)    ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
150 #define NEXT()  (p->next++)
151 #define NEXT2() (p->next += 2)
152 #define NEXTn(n)        (p->next += (n))
153 #define GETNEXT()       (*p->next++)
154 #define SETERROR(e)     seterr(p, (e))
155 #define REQUIRE(co, e)  ((co) || SETERROR(e))
156 #define MUSTSEE(c, e)   (REQUIRE(MORE() && PEEK() == (c), e))
157 #define MUSTEAT(c, e)   (REQUIRE(MORE() && GETNEXT() == (c), e))
158 #define MUSTNOTSEE(c, e)        (REQUIRE(!MORE() || PEEK() != (c), e))
159 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
160 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
161 #define AHEAD(pos)              dofwd(p, pos, HERE()-(pos))
162 #define ASTERN(sop, pos)        EMIT(sop, HERE()-pos)
163 #define HERE()          (p->slen)
164 #define THERE()         (p->slen - 1)
165 #define THERETHERE()    (p->slen - 2)
166 #define DROP(n) (p->slen -= (n))
167
168 #ifndef NDEBUG
169 static int never = 0;           /* for use in asserts; shuts lint up */
170 #else
171 #define never   0               /* some <assert.h>s have bugs too */
172 #endif
173
174 /* Macro used by computejump()/computematchjump() */
175 #define MIN(a,b)        ((a)<(b)?(a):(b))
176
177 /*
178  - regcomp - interface for parser and compilation
179  = extern int regcomp(regex_t *, const char *, int);
180  = #define      REG_BASIC       0000
181  = #define      REG_EXTENDED    0001
182  = #define      REG_ICASE       0002
183  = #define      REG_NOSUB       0004
184  = #define      REG_NEWLINE     0010
185  = #define      REG_NOSPEC      0020
186  = #define      REG_PEND        0040
187  = #define      REG_DUMP        0200
188  */
189 int                             /* 0 success, otherwise REG_something */
190 regcomp(regex_t *preg, const char *pattern, int cflags)
191 {
192         struct parse pa;
193         struct re_guts *g;
194         struct parse *p = &pa;
195         int i;
196         size_t len;
197 #ifdef REDEBUG
198 #       define  GOODFLAGS(f)    (f)
199 #else
200 #       define  GOODFLAGS(f)    ((f)&~REG_DUMP)
201 #endif
202
203         cflags = GOODFLAGS(cflags);
204         if ((cflags&REG_EXTENDED) && (cflags&REG_NOSPEC))
205                 return(REG_INVARG);
206
207         if (cflags&REG_PEND) {
208                 if (preg->re_endp < pattern)
209                         return(REG_INVARG);
210                 len = preg->re_endp - pattern;
211         } else
212                 len = strlen((char *)pattern);
213
214         /* do the mallocs early so failure handling is easy */
215         g = (struct re_guts *)malloc(sizeof(struct re_guts) +
216                                                         (NC-1)*sizeof(cat_t));
217         if (g == NULL)
218                 return(REG_ESPACE);
219         p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
220         p->strip = (sop *)malloc(p->ssize * sizeof(sop));
221         p->slen = 0;
222         if (p->strip == NULL) {
223                 free((char *)g);
224                 return(REG_ESPACE);
225         }
226
227         /* set things up */
228         p->g = g;
229         p->next = (char *)pattern;      /* convenience; we do not modify it */
230         p->end = p->next + len;
231         p->error = 0;
232         p->ncsalloc = 0;
233         for (i = 0; i < NPAREN; i++) {
234                 p->pbegin[i] = 0;
235                 p->pend[i] = 0;
236         }
237         g->csetsize = NC;
238         g->sets = NULL;
239         g->setbits = NULL;
240         g->ncsets = 0;
241         g->cflags = cflags;
242         g->iflags = 0;
243         g->nbol = 0;
244         g->neol = 0;
245         g->must = NULL;
246         g->moffset = -1;
247         g->charjump = NULL;
248         g->matchjump = NULL;
249         g->mlen = 0;
250         g->nsub = 0;
251         g->ncategories = 1;     /* category 0 is "everything else" */
252         g->categories = &g->catspace[-(CHAR_MIN)];
253         (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
254         g->backrefs = 0;
255
256         /* do it */
257         EMIT(OEND, 0);
258         g->firststate = THERE();
259         if (cflags&REG_EXTENDED)
260                 p_ere(p, OUT);
261         else if (cflags&REG_NOSPEC)
262                 p_str(p);
263         else
264                 p_bre(p, OUT, OUT);
265         EMIT(OEND, 0);
266         g->laststate = THERE();
267
268         /* tidy up loose ends and fill things in */
269         categorize(p, g);
270         stripsnug(p, g);
271         findmust(p, g);
272         /* only use Boyer-Moore algorithm if the pattern is bigger
273          * than three characters
274          */
275         if(g->mlen > 3) {
276                 computejumps(p, g);
277                 computematchjumps(p, g);
278                 if(g->matchjump == NULL && g->charjump != NULL) {
279                         free(g->charjump);
280                         g->charjump = NULL;
281                 }
282         }
283         g->nplus = pluscount(p, g);
284         g->magic = MAGIC2;
285         preg->re_nsub = g->nsub;
286         preg->re_g = g;
287         preg->re_magic = MAGIC1;
288 #ifndef REDEBUG
289         /* not debugging, so can't rely on the assert() in regexec() */
290         if (g->iflags&BAD)
291                 SETERROR(REG_ASSERT);
292 #endif
293
294         /* win or lose, we're done */
295         if (p->error != 0)      /* lose */
296                 regfree(preg);
297         return(p->error);
298 }
299
300 /*
301  - p_ere - ERE parser top level, concatenation and alternation
302  == static void p_ere(struct parse *p, int stop);
303  */
304 static void
305 p_ere(struct parse *p,
306       int stop)                 /* character this ERE should end at */
307 {
308         char c;
309         sopno prevback;
310         sopno prevfwd;
311         sopno conc;
312         int first = 1;          /* is this the first alternative? */
313
314         for (;;) {
315                 /* do a bunch of concatenated expressions */
316                 conc = HERE();
317                 while (MORE() && (c = PEEK()) != '|' && c != stop)
318                         p_ere_exp(p);
319                 (void)REQUIRE(HERE() != conc, REG_EMPTY);       /* require nonempty */
320
321                 if (!EAT('|'))
322                         break;          /* NOTE BREAK OUT */
323
324                 if (first) {
325                         INSERT(OCH_, conc);     /* offset is wrong */
326                         prevfwd = conc;
327                         prevback = conc;
328                         first = 0;
329                 }
330                 ASTERN(OOR1, prevback);
331                 prevback = THERE();
332                 AHEAD(prevfwd);                 /* fix previous offset */
333                 prevfwd = HERE();
334                 EMIT(OOR2, 0);                  /* offset is very wrong */
335         }
336
337         if (!first) {           /* tail-end fixups */
338                 AHEAD(prevfwd);
339                 ASTERN(O_CH, prevback);
340         }
341
342         assert(!MORE() || SEE(stop));
343 }
344
345 /*
346  - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
347  == static void p_ere_exp(struct parse *p);
348  */
349 static void
350 p_ere_exp(struct parse *p)
351 {
352         char c;
353         sopno pos;
354         int count;
355         int count2;
356         sopno subno;
357         int wascaret = 0;
358
359         assert(MORE());         /* caller should have ensured this */
360         c = GETNEXT();
361
362         pos = HERE();
363         switch (c) {
364         case '(':
365                 (void)REQUIRE(MORE(), REG_EPAREN);
366                 p->g->nsub++;
367                 subno = p->g->nsub;
368                 if (subno < NPAREN)
369                         p->pbegin[subno] = HERE();
370                 EMIT(OLPAREN, subno);
371                 if (!SEE(')'))
372                         p_ere(p, ')');
373                 if (subno < NPAREN) {
374                         p->pend[subno] = HERE();
375                         assert(p->pend[subno] != 0);
376                 }
377                 EMIT(ORPAREN, subno);
378                 (void)MUSTEAT(')', REG_EPAREN);
379                 break;
380 #ifndef POSIX_MISTAKE
381         case ')':               /* happens only if no current unmatched ( */
382                 /*
383                  * You may ask, why the ifndef?  Because I didn't notice
384                  * this until slightly too late for 1003.2, and none of the
385                  * other 1003.2 regular-expression reviewers noticed it at
386                  * all.  So an unmatched ) is legal POSIX, at least until
387                  * we can get it fixed.
388                  */
389                 SETERROR(REG_EPAREN);
390                 break;
391 #endif
392         case '^':
393                 EMIT(OBOL, 0);
394                 p->g->iflags |= USEBOL;
395                 p->g->nbol++;
396                 wascaret = 1;
397                 break;
398         case '$':
399                 EMIT(OEOL, 0);
400                 p->g->iflags |= USEEOL;
401                 p->g->neol++;
402                 break;
403         case '|':
404                 SETERROR(REG_EMPTY);
405                 break;
406         case '*':
407         case '+':
408         case '?':
409                 SETERROR(REG_BADRPT);
410                 break;
411         case '.':
412                 if (p->g->cflags&REG_NEWLINE)
413                         nonnewline(p);
414                 else
415                         EMIT(OANY, 0);
416                 break;
417         case '[':
418                 p_bracket(p);
419                 break;
420         case '\\':
421                 (void)REQUIRE(MORE(), REG_EESCAPE);
422                 c = GETNEXT();
423                 ordinary(p, c);
424                 break;
425         case '{':               /* okay as ordinary except if digit follows */
426                 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
427                 /* FALLTHROUGH */
428         default:
429                 ordinary(p, c);
430                 break;
431         }
432
433         if (!MORE())
434                 return;
435         c = PEEK();
436         /* we call { a repetition if followed by a digit */
437         if (!( c == '*' || c == '+' || c == '?' ||
438                                 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
439                 return;         /* no repetition, we're done */
440         NEXT();
441
442         (void)REQUIRE(!wascaret, REG_BADRPT);
443         switch (c) {
444         case '*':       /* implemented as +? */
445                 /* this case does not require the (y|) trick, noKLUDGE */
446                 INSERT(OPLUS_, pos);
447                 ASTERN(O_PLUS, pos);
448                 INSERT(OQUEST_, pos);
449                 ASTERN(O_QUEST, pos);
450                 break;
451         case '+':
452                 INSERT(OPLUS_, pos);
453                 ASTERN(O_PLUS, pos);
454                 break;
455         case '?':
456                 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
457                 INSERT(OCH_, pos);              /* offset slightly wrong */
458                 ASTERN(OOR1, pos);              /* this one's right */
459                 AHEAD(pos);                     /* fix the OCH_ */
460                 EMIT(OOR2, 0);                  /* offset very wrong... */
461                 AHEAD(THERE());                 /* ...so fix it */
462                 ASTERN(O_CH, THERETHERE());
463                 break;
464         case '{':
465                 count = p_count(p);
466                 if (EAT(',')) {
467                         if (isdigit((uch)PEEK())) {
468                                 count2 = p_count(p);
469                                 (void)REQUIRE(count <= count2, REG_BADBR);
470                         } else          /* single number with comma */
471                                 count2 = INFINITY;
472                 } else          /* just a single number */
473                         count2 = count;
474                 repeat(p, pos, count, count2);
475                 if (!EAT('}')) {        /* error heuristics */
476                         while (MORE() && PEEK() != '}')
477                                 NEXT();
478                         (void)REQUIRE(MORE(), REG_EBRACE);
479                         SETERROR(REG_BADBR);
480                 }
481                 break;
482         }
483
484         if (!MORE())
485                 return;
486         c = PEEK();
487         if (!( c == '*' || c == '+' || c == '?' ||
488                                 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
489                 return;
490         SETERROR(REG_BADRPT);
491 }
492
493 /*
494  - p_str - string (no metacharacters) "parser"
495  == static void p_str(struct parse *p);
496  */
497 static void
498 p_str(struct parse *p)
499 {
500         (void)REQUIRE(MORE(), REG_EMPTY);
501         while (MORE())
502                 ordinary(p, GETNEXT());
503 }
504
505 /*
506  - p_bre - BRE parser top level, anchoring and concatenation
507  == static void p_bre(struct parse *p, int end1, \
508  ==     int end2);
509  * Giving end1 as OUT essentially eliminates the end1/end2 check.
510  *
511  * This implementation is a bit of a kludge, in that a trailing $ is first
512  * taken as an ordinary character and then revised to be an anchor.  The
513  * only undesirable side effect is that '$' gets included as a character
514  * category in such cases.  This is fairly harmless; not worth fixing.
515  * The amount of lookahead needed to avoid this kludge is excessive.
516  */
517 static void
518 p_bre(struct parse *p,
519       int end1,                 /* first terminating character */
520       int end2)                 /* second terminating character */
521 {
522         sopno start = HERE();
523         int first = 1;                  /* first subexpression? */
524         int wasdollar = 0;
525
526         if (EAT('^')) {
527                 EMIT(OBOL, 0);
528                 p->g->iflags |= USEBOL;
529                 p->g->nbol++;
530         }
531         while (MORE() && !SEETWO(end1, end2)) {
532                 wasdollar = p_simp_re(p, first);
533                 first = 0;
534         }
535         if (wasdollar) {        /* oops, that was a trailing anchor */
536                 DROP(1);
537                 EMIT(OEOL, 0);
538                 p->g->iflags |= USEEOL;
539                 p->g->neol++;
540         }
541
542         (void)REQUIRE(HERE() != start, REG_EMPTY);      /* require nonempty */
543 }
544
545 /*
546  - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
547  == static int p_simp_re(struct parse *p, int starordinary);
548  */
549 static int                      /* was the simple RE an unbackslashed $? */
550 p_simp_re(struct parse *p,
551           int starordinary)     /* is a leading * an ordinary character? */
552 {
553         int c;
554         int count;
555         int count2;
556         sopno pos;
557         int i;
558         sopno subno;
559 #       define  BACKSL  (1<<CHAR_BIT)
560
561         pos = HERE();           /* repetion op, if any, covers from here */
562
563         assert(MORE());         /* caller should have ensured this */
564         c = GETNEXT();
565         if (c == '\\') {
566                 (void)REQUIRE(MORE(), REG_EESCAPE);
567                 c = BACKSL | GETNEXT();
568         }
569         switch (c) {
570         case '.':
571                 if (p->g->cflags&REG_NEWLINE)
572                         nonnewline(p);
573                 else
574                         EMIT(OANY, 0);
575                 break;
576         case '[':
577                 p_bracket(p);
578                 break;
579         case BACKSL|'{':
580                 SETERROR(REG_BADRPT);
581                 break;
582         case BACKSL|'(':
583                 p->g->nsub++;
584                 subno = p->g->nsub;
585                 if (subno < NPAREN)
586                         p->pbegin[subno] = HERE();
587                 EMIT(OLPAREN, subno);
588                 /* the MORE here is an error heuristic */
589                 if (MORE() && !SEETWO('\\', ')'))
590                         p_bre(p, '\\', ')');
591                 if (subno < NPAREN) {
592                         p->pend[subno] = HERE();
593                         assert(p->pend[subno] != 0);
594                 }
595                 EMIT(ORPAREN, subno);
596                 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
597                 break;
598         case BACKSL|')':        /* should not get here -- must be user */
599         case BACKSL|'}':
600                 SETERROR(REG_EPAREN);
601                 break;
602         case BACKSL|'1':
603         case BACKSL|'2':
604         case BACKSL|'3':
605         case BACKSL|'4':
606         case BACKSL|'5':
607         case BACKSL|'6':
608         case BACKSL|'7':
609         case BACKSL|'8':
610         case BACKSL|'9':
611                 i = (c&~BACKSL) - '0';
612                 assert(i < NPAREN);
613                 if (p->pend[i] != 0) {
614                         assert(i <= p->g->nsub);
615                         EMIT(OBACK_, i);
616                         assert(p->pbegin[i] != 0);
617                         assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
618                         assert(OP(p->strip[p->pend[i]]) == ORPAREN);
619                         (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
620                         EMIT(O_BACK, i);
621                 } else
622                         SETERROR(REG_ESUBREG);
623                 p->g->backrefs = 1;
624                 break;
625         case '*':
626                 (void)REQUIRE(starordinary, REG_BADRPT);
627                 /* FALLTHROUGH */
628         default:
629                 ordinary(p, (char)c);
630                 break;
631         }
632
633         if (EAT('*')) {         /* implemented as +? */
634                 /* this case does not require the (y|) trick, noKLUDGE */
635                 INSERT(OPLUS_, pos);
636                 ASTERN(O_PLUS, pos);
637                 INSERT(OQUEST_, pos);
638                 ASTERN(O_QUEST, pos);
639         } else if (EATTWO('\\', '{')) {
640                 count = p_count(p);
641                 if (EAT(',')) {
642                         if (MORE() && isdigit((uch)PEEK())) {
643                                 count2 = p_count(p);
644                                 (void)REQUIRE(count <= count2, REG_BADBR);
645                         } else          /* single number with comma */
646                                 count2 = INFINITY;
647                 } else          /* just a single number */
648                         count2 = count;
649                 repeat(p, pos, count, count2);
650                 if (!EATTWO('\\', '}')) {       /* error heuristics */
651                         while (MORE() && !SEETWO('\\', '}'))
652                                 NEXT();
653                         (void)REQUIRE(MORE(), REG_EBRACE);
654                         SETERROR(REG_BADBR);
655                 }
656         } else if (c == '$')     /* $ (but not \$) ends it */
657                 return(1);
658
659         return(0);
660 }
661
662 /*
663  - p_count - parse a repetition count
664  == static int p_count(struct parse *p);
665  */
666 static int                      /* the value */
667 p_count(struct parse *p)
668 {
669         int count = 0;
670         int ndigits = 0;
671
672         while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
673                 count = count*10 + (GETNEXT() - '0');
674                 ndigits++;
675         }
676
677         (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
678         return(count);
679 }
680
681 /*
682  - p_bracket - parse a bracketed character list
683  == static void p_bracket(struct parse *p);
684  *
685  * Note a significant property of this code:  if the allocset() did SETERROR,
686  * no set operations are done.
687  */
688 static void
689 p_bracket(struct parse *p)
690 {
691         cset *cs = allocset(p);
692         int invert = 0;
693
694         /* Dept of Truly Sickening Special-Case Kludges */
695         if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
696                 EMIT(OBOW, 0);
697                 NEXTn(6);
698                 return;
699         }
700         if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
701                 EMIT(OEOW, 0);
702                 NEXTn(6);
703                 return;
704         }
705
706         if (EAT('^'))
707                 invert++;       /* make note to invert set at end */
708         if (EAT(']'))
709                 CHadd(cs, ']');
710         else if (EAT('-'))
711                 CHadd(cs, '-');
712         while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
713                 p_b_term(p, cs);
714         if (EAT('-'))
715                 CHadd(cs, '-');
716         (void)MUSTEAT(']', REG_EBRACK);
717
718         if (p->error != 0)      /* don't mess things up further */
719                 return;
720
721         if (p->g->cflags&REG_ICASE) {
722                 int i;
723                 int ci;
724
725                 for (i = p->g->csetsize - 1; i >= 0; i--)
726                         if (CHIN(cs, i) && isalpha(i)) {
727                                 ci = othercase(i);
728                                 if (ci != i)
729                                         CHadd(cs, ci);
730                         }
731                 if (cs->multis != NULL)
732                         mccase(p, cs);
733         }
734         if (invert) {
735                 int i;
736
737                 for (i = p->g->csetsize - 1; i >= 0; i--)
738                         if (CHIN(cs, i))
739                                 CHsub(cs, i);
740                         else
741                                 CHadd(cs, i);
742                 if (p->g->cflags&REG_NEWLINE)
743                         CHsub(cs, '\n');
744                 if (cs->multis != NULL)
745                         mcinvert(p, cs);
746         }
747
748         assert(cs->multis == NULL);             /* xxx */
749
750         if (nch(p, cs) == 1) {          /* optimize singleton sets */
751                 ordinary(p, firstch(p, cs));
752                 freeset(p, cs);
753         } else
754                 EMIT(OANYOF, freezeset(p, cs));
755 }
756
757 /*
758  - p_b_term - parse one term of a bracketed character list
759  == static void p_b_term(struct parse *p, cset *cs);
760  */
761 static void
762 p_b_term(struct parse *p, cset *cs)
763 {
764         char c;
765         char start, finish;
766         int i;
767
768         /* classify what we've got */
769         switch ((MORE()) ? PEEK() : '\0') {
770         case '[':
771                 c = (MORE2()) ? PEEK2() : '\0';
772                 break;
773         case '-':
774                 SETERROR(REG_ERANGE);
775                 return;                 /* NOTE RETURN */
776                 break;
777         default:
778                 c = '\0';
779                 break;
780         }
781
782         switch (c) {
783         case ':':               /* character class */
784                 NEXT2();
785                 (void)REQUIRE(MORE(), REG_EBRACK);
786                 c = PEEK();
787                 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
788                 p_b_cclass(p, cs);
789                 (void)REQUIRE(MORE(), REG_EBRACK);
790                 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
791                 break;
792         case '=':               /* equivalence class */
793                 NEXT2();
794                 (void)REQUIRE(MORE(), REG_EBRACK);
795                 c = PEEK();
796                 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
797                 p_b_eclass(p, cs);
798                 (void)REQUIRE(MORE(), REG_EBRACK);
799                 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
800                 break;
801         default:                /* symbol, ordinary character, or range */
802 /* xxx revision needed for multichar stuff */
803                 start = p_b_symbol(p);
804                 if (SEE('-') && MORE2() && PEEK2() != ']') {
805                         /* range */
806                         NEXT();
807                         if (EAT('-'))
808                                 finish = '-';
809                         else
810                                 finish = p_b_symbol(p);
811                 } else
812                         finish = start;
813                 if (start == finish)
814                         CHadd(cs, start);
815                 else {
816                         if (__collate_load_error) {
817                                 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
818                                 for (i = (uch)start; i <= (uch)finish; i++)
819                                         CHadd(cs, i);
820                         } else {
821                                 (void)REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE);
822                                 for (i = CHAR_MIN; i <= CHAR_MAX; i++) {
823                                         if (   __collate_range_cmp(start, i) <= 0
824                                             && __collate_range_cmp(i, finish) <= 0
825                                            )
826                                                 CHadd(cs, i);
827                                 }
828                         }
829                 }
830                 break;
831         }
832 }
833
834 /*
835  - p_b_cclass - parse a character-class name and deal with it
836  == static void p_b_cclass(struct parse *p, cset *cs);
837  */
838 static void
839 p_b_cclass(struct parse *p, cset *cs)
840 {
841         int c;
842         char *sp = p->next;
843         struct cclass *cp;
844         size_t len;
845
846         while (MORE() && isalpha((uch)PEEK()))
847                 NEXT();
848         len = p->next - sp;
849         for (cp = cclasses; cp->name != NULL; cp++)
850                 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
851                         break;
852         if (cp->name == NULL) {
853                 /* oops, didn't find it */
854                 SETERROR(REG_ECTYPE);
855                 return;
856         }
857
858         switch (cp->fidx) {
859         case CALNUM:
860                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
861                         if (isalnum((uch)c))
862                                 CHadd(cs, c);
863                 break;
864         case CALPHA:
865                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
866                         if (isalpha((uch)c))
867                                 CHadd(cs, c);
868                 break;
869         case CBLANK:
870                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
871                         if (isblank((uch)c))
872                                 CHadd(cs, c);
873                 break;
874         case CCNTRL:
875                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
876                         if (iscntrl((uch)c))
877                                 CHadd(cs, c);
878                 break;
879         case CDIGIT:
880                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
881                         if (isdigit((uch)c))
882                                 CHadd(cs, c);
883                 break;
884         case CGRAPH:
885                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
886                         if (isgraph((uch)c))
887                                 CHadd(cs, c);
888                 break;
889         case CLOWER:
890                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
891                         if (islower((uch)c))
892                                 CHadd(cs, c);
893                 break;
894         case CPRINT:
895                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
896                         if (isprint((uch)c))
897                                 CHadd(cs, c);
898                 break;
899         case CPUNCT:
900                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
901                         if (ispunct((uch)c))
902                                 CHadd(cs, c);
903                 break;
904         case CSPACE:
905                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
906                         if (isspace((uch)c))
907                                 CHadd(cs, c);
908                 break;
909         case CUPPER:
910                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
911                         if (isupper((uch)c))
912                                 CHadd(cs, c);
913                 break;
914         case CXDIGIT:
915                 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
916                         if (isxdigit((uch)c))
917                                 CHadd(cs, c);
918                 break;
919         }
920 #if 0
921         for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
922                 MCadd(p, cs, u);
923 #endif
924 }
925
926 /*
927  - p_b_eclass - parse an equivalence-class name and deal with it
928  == static void p_b_eclass(struct parse *p, cset *cs);
929  *
930  * This implementation is incomplete. xxx
931  */
932 static void
933 p_b_eclass(struct parse *p, cset *cs)
934 {
935         char c;
936
937         c = p_b_coll_elem(p, '=');
938         CHadd(cs, c);
939 }
940
941 /*
942  - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
943  == static char p_b_symbol(struct parse *p);
944  */
945 static char                     /* value of symbol */
946 p_b_symbol(struct parse *p)
947 {
948         char value;
949
950         (void)REQUIRE(MORE(), REG_EBRACK);
951         if (!EATTWO('[', '.'))
952                 return(GETNEXT());
953
954         /* collating symbol */
955         value = p_b_coll_elem(p, '.');
956         (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
957         return(value);
958 }
959
960 /*
961  - p_b_coll_elem - parse a collating-element name and look it up
962  == static char p_b_coll_elem(struct parse *p, int endc);
963  */
964 static char                     /* value of collating element */
965 p_b_coll_elem(struct parse *p,
966     int endc)                   /* name ended by endc,']' */
967 {
968         char *sp = p->next;
969         struct cname *cp;
970         int len;
971
972         while (MORE() && !SEETWO(endc, ']'))
973                 NEXT();
974         if (!MORE()) {
975                 SETERROR(REG_EBRACK);
976                 return(0);
977         }
978         len = p->next - sp;
979         for (cp = cnames; cp->name != NULL; cp++)
980                 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
981                         return(cp->code);       /* known name */
982         if (len == 1)
983                 return(*sp);    /* single character */
984         SETERROR(REG_ECOLLATE);                 /* neither */
985         return(0);
986 }
987
988 /*
989  - othercase - return the case counterpart of an alphabetic
990  == static char othercase(int ch);
991  */
992 static char                     /* if no counterpart, return ch */
993 othercase(int ch)
994 {
995         ch = (uch)ch;
996         assert(isalpha(ch));
997         if (isupper(ch))
998                 return(tolower(ch));
999         else if (islower(ch))
1000                 return(toupper(ch));
1001         else                    /* peculiar, but could happen */
1002                 return(ch);
1003 }
1004
1005 /*
1006  - bothcases - emit a dualcase version of a two-case character
1007  == static void bothcases(struct parse *p, int ch);
1008  *
1009  * Boy, is this implementation ever a kludge...
1010  */
1011 static void
1012 bothcases(struct parse *p, int ch)
1013 {
1014         char *oldnext = p->next;
1015         char *oldend = p->end;
1016         char bracket[3];
1017
1018         ch = (uch)ch;
1019         assert(othercase(ch) != ch);    /* p_bracket() would recurse */
1020         p->next = bracket;
1021         p->end = bracket+2;
1022         bracket[0] = ch;
1023         bracket[1] = ']';
1024         bracket[2] = '\0';
1025         p_bracket(p);
1026         assert(p->next == bracket+2);
1027         p->next = oldnext;
1028         p->end = oldend;
1029 }
1030
1031 /*
1032  - ordinary - emit an ordinary character
1033  == static void ordinary(struct parse *p, int ch);
1034  */
1035 static void
1036 ordinary(struct parse *p, int ch)
1037 {
1038         cat_t *cap = p->g->categories;
1039
1040         if ((p->g->cflags&REG_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
1041                 bothcases(p, ch);
1042         else {
1043                 EMIT(OCHAR, (uch)ch);
1044                 if (cap[ch] == 0)
1045                         cap[ch] = p->g->ncategories++;
1046         }
1047 }
1048
1049 /*
1050  - nonnewline - emit REG_NEWLINE version of OANY
1051  == static void nonnewline(struct parse *p);
1052  *
1053  * Boy, is this implementation ever a kludge...
1054  */
1055 static void
1056 nonnewline(struct parse *p)
1057 {
1058         char *oldnext = p->next;
1059         char *oldend = p->end;
1060         char bracket[4];
1061
1062         p->next = bracket;
1063         p->end = bracket+3;
1064         bracket[0] = '^';
1065         bracket[1] = '\n';
1066         bracket[2] = ']';
1067         bracket[3] = '\0';
1068         p_bracket(p);
1069         assert(p->next == bracket+3);
1070         p->next = oldnext;
1071         p->end = oldend;
1072 }
1073
1074 /*
1075  - repeat - generate code for a bounded repetition, recursively if needed
1076  == static void repeat(struct parse *p, sopno start, int from, int to);
1077  */
1078 static void
1079 repeat(struct parse *p,
1080        sopno start,             /* operand from here to end of strip */
1081        int from,                /* repeated from this number */
1082        int to)                  /* to this number of times (maybe INFINITY) */
1083 {
1084         sopno finish = HERE();
1085 #       define  N       2
1086 #       define  INF     3
1087 #       define  REP(f, t)       ((f)*8 + (t))
1088 #       define  MAP(n)  (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1089         sopno copy;
1090
1091         if (p->error != 0)      /* head off possible runaway recursion */
1092                 return;
1093
1094         assert(from <= to);
1095
1096         switch (REP(MAP(from), MAP(to))) {
1097         case REP(0, 0):                 /* must be user doing this */
1098                 DROP(finish-start);     /* drop the operand */
1099                 break;
1100         case REP(0, 1):                 /* as x{1,1}? */
1101         case REP(0, N):                 /* as x{1,n}? */
1102         case REP(0, INF):               /* as x{1,}? */
1103                 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1104                 INSERT(OCH_, start);            /* offset is wrong... */
1105                 repeat(p, start+1, 1, to);
1106                 ASTERN(OOR1, start);
1107                 AHEAD(start);                   /* ... fix it */
1108                 EMIT(OOR2, 0);
1109                 AHEAD(THERE());
1110                 ASTERN(O_CH, THERETHERE());
1111                 break;
1112         case REP(1, 1):                 /* trivial case */
1113                 /* done */
1114                 break;
1115         case REP(1, N):                 /* as x?x{1,n-1} */
1116                 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1117                 INSERT(OCH_, start);
1118                 ASTERN(OOR1, start);
1119                 AHEAD(start);
1120                 EMIT(OOR2, 0);                  /* offset very wrong... */
1121                 AHEAD(THERE());                 /* ...so fix it */
1122                 ASTERN(O_CH, THERETHERE());
1123                 copy = dupl(p, start+1, finish+1);
1124                 assert(copy == finish+4);
1125                 repeat(p, copy, 1, to-1);
1126                 break;
1127         case REP(1, INF):               /* as x+ */
1128                 INSERT(OPLUS_, start);
1129                 ASTERN(O_PLUS, start);
1130                 break;
1131         case REP(N, N):                 /* as xx{m-1,n-1} */
1132                 copy = dupl(p, start, finish);
1133                 repeat(p, copy, from-1, to-1);
1134                 break;
1135         case REP(N, INF):               /* as xx{n-1,INF} */
1136                 copy = dupl(p, start, finish);
1137                 repeat(p, copy, from-1, to);
1138                 break;
1139         default:                        /* "can't happen" */
1140                 SETERROR(REG_ASSERT);   /* just in case */
1141                 break;
1142         }
1143 }
1144
1145 /*
1146  - seterr - set an error condition
1147  == static int seterr(struct parse *p, int e);
1148  */
1149 static int                      /* useless but makes type checking happy */
1150 seterr(struct parse *p, int e)
1151 {
1152         if (p->error == 0)      /* keep earliest error condition */
1153                 p->error = e;
1154         p->next = nuls;         /* try to bring things to a halt */
1155         p->end = nuls;
1156         return(0);              /* make the return value well-defined */
1157 }
1158
1159 /*
1160  - allocset - allocate a set of characters for []
1161  == static cset *allocset(struct parse *p);
1162  */
1163 static cset *
1164 allocset(struct parse *p)
1165 {
1166         int no = p->g->ncsets++;
1167         size_t nc;
1168         size_t nbytes;
1169         cset *cs;
1170         size_t css = (size_t)p->g->csetsize;
1171         int i;
1172
1173         if (no >= p->ncsalloc) {        /* need another column of space */
1174                 p->ncsalloc += CHAR_BIT;
1175                 nc = p->ncsalloc;
1176                 assert(nc % CHAR_BIT == 0);
1177                 nbytes = nc / CHAR_BIT * css;
1178                 if (p->g->sets == NULL)
1179                         p->g->sets = (cset *)malloc(nc * sizeof(cset));
1180                 else
1181                         p->g->sets = (cset *)reallocf((char *)p->g->sets,
1182                                                         nc * sizeof(cset));
1183                 if (p->g->setbits == NULL)
1184                         p->g->setbits = (uch *)malloc(nbytes);
1185                 else {
1186                         p->g->setbits = (uch *)reallocf((char *)p->g->setbits,
1187                                                                 nbytes);
1188                         /* xxx this isn't right if setbits is now NULL */
1189                         for (i = 0; i < no; i++)
1190                                 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1191                 }
1192                 if (p->g->sets != NULL && p->g->setbits != NULL)
1193                         (void) memset((char *)p->g->setbits + (nbytes - css),
1194                                                                 0, css);
1195                 else {
1196                         no = 0;
1197                         SETERROR(REG_ESPACE);
1198                         /* caller's responsibility not to do set ops */
1199                 }
1200         }
1201
1202         assert(p->g->sets != NULL);     /* xxx */
1203         cs = &p->g->sets[no];
1204         cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1205         cs->mask = 1 << ((no) % CHAR_BIT);
1206         cs->hash = 0;
1207         cs->smultis = 0;
1208         cs->multis = NULL;
1209
1210         return(cs);
1211 }
1212
1213 /*
1214  - freeset - free a now-unused set
1215  == static void freeset(struct parse *p, cset *cs);
1216  */
1217 static void
1218 freeset(struct parse *p, cset *cs)
1219 {
1220         int i;
1221         cset *top = &p->g->sets[p->g->ncsets];
1222         size_t css = (size_t)p->g->csetsize;
1223
1224         for (i = 0; i < css; i++)
1225                 CHsub(cs, i);
1226         if (cs == top-1)        /* recover only the easy case */
1227                 p->g->ncsets--;
1228 }
1229
1230 /*
1231  - freezeset - final processing on a set of characters
1232  == static int freezeset(struct parse *p, cset *cs);
1233  *
1234  * The main task here is merging identical sets.  This is usually a waste
1235  * of time (although the hash code minimizes the overhead), but can win
1236  * big if REG_ICASE is being used.  REG_ICASE, by the way, is why the hash
1237  * is done using addition rather than xor -- all ASCII [aA] sets xor to
1238  * the same value!
1239  */
1240 static int                      /* set number */
1241 freezeset(struct parse *p, cset *cs)
1242 {
1243         short h = cs->hash;
1244         int i;
1245         cset *top = &p->g->sets[p->g->ncsets];
1246         cset *cs2;
1247         size_t css = (size_t)p->g->csetsize;
1248
1249         /* look for an earlier one which is the same */
1250         for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1251                 if (cs2->hash == h && cs2 != cs) {
1252                         /* maybe */
1253                         for (i = 0; i < css; i++)
1254                                 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1255                                         break;          /* no */
1256                         if (i == css)
1257                                 break;                  /* yes */
1258                 }
1259
1260         if (cs2 < top) {        /* found one */
1261                 freeset(p, cs);
1262                 cs = cs2;
1263         }
1264
1265         return((int)(cs - p->g->sets));
1266 }
1267
1268 /*
1269  - firstch - return first character in a set (which must have at least one)
1270  == static int firstch(struct parse *p, cset *cs);
1271  */
1272 static int                      /* character; there is no "none" value */
1273 firstch(struct parse *p, cset *cs)
1274 {
1275         int i;
1276         size_t css = (size_t)p->g->csetsize;
1277
1278         for (i = 0; i < css; i++)
1279                 if (CHIN(cs, i))
1280                         return((char)i);
1281         assert(never);
1282         return(0);              /* arbitrary */
1283 }
1284
1285 /*
1286  - nch - number of characters in a set
1287  == static int nch(struct parse *p, cset *cs);
1288  */
1289 static int
1290 nch(struct parse *p, cset *cs)
1291 {
1292         int i;
1293         size_t css = (size_t)p->g->csetsize;
1294         int n = 0;
1295
1296         for (i = 0; i < css; i++)
1297                 if (CHIN(cs, i))
1298                         n++;
1299         return(n);
1300 }
1301
1302 /*
1303  - mcadd - add a collating element to a cset
1304  == static void mcadd(struct parse *p, cset *cs, \
1305  ==     char *cp);
1306  */
1307 static void
1308 mcadd(struct parse *p, cset *cs, char *cp)
1309 {
1310         size_t oldend = cs->smultis;
1311
1312         cs->smultis += strlen(cp) + 1;
1313         if (cs->multis == NULL)
1314                 cs->multis = malloc(cs->smultis);
1315         else
1316                 cs->multis = reallocf(cs->multis, cs->smultis);
1317         if (cs->multis == NULL) {
1318                 SETERROR(REG_ESPACE);
1319                 return;
1320         }
1321
1322         (void) strcpy(cs->multis + oldend - 1, cp);
1323         cs->multis[cs->smultis - 1] = '\0';
1324 }
1325
1326 #if used
1327 /*
1328  - mcsub - subtract a collating element from a cset
1329  == static void mcsub(cset *cs, char *cp);
1330  */
1331 static void
1332 mcsub(cset *cs, char *cp)
1333 {
1334         char *fp = mcfind(cs, cp);
1335         size_t len = strlen(fp);
1336
1337         assert(fp != NULL);
1338         (void) memmove(fp, fp + len + 1,
1339                                 cs->smultis - (fp + len + 1 - cs->multis));
1340         cs->smultis -= len;
1341
1342         if (cs->smultis == 0) {
1343                 free(cs->multis);
1344                 cs->multis = NULL;
1345                 return;
1346         }
1347
1348         cs->multis = reallocf(cs->multis, cs->smultis);
1349         assert(cs->multis != NULL);
1350 }
1351
1352 /*
1353  - mcin - is a collating element in a cset?
1354  == static int mcin(cset *cs, char *cp);
1355  */
1356 static int
1357 mcin(cset *cs, char *cp)
1358 {
1359         return(mcfind(cs, cp) != NULL);
1360 }
1361
1362 /*
1363  - mcfind - find a collating element in a cset
1364  == static char *mcfind(cset *cs, char *cp);
1365  */
1366 static char *
1367 mcfind(cset *cs, char *cp)
1368 {
1369         char *p;
1370
1371         if (cs->multis == NULL)
1372                 return(NULL);
1373         for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
1374                 if (strcmp(cp, p) == 0)
1375                         return(p);
1376         return(NULL);
1377 }
1378 #endif
1379
1380 /*
1381  - mcinvert - invert the list of collating elements in a cset
1382  == static void mcinvert(struct parse *p, cset *cs);
1383  *
1384  * This would have to know the set of possibilities.  Implementation
1385  * is deferred.
1386  */
1387 static void
1388 mcinvert(struct parse *p, cset *cs)
1389 {
1390         assert(cs->multis == NULL);     /* xxx */
1391 }
1392
1393 /*
1394  - mccase - add case counterparts of the list of collating elements in a cset
1395  == static void mccase(struct parse *p, cset *cs);
1396  *
1397  * This would have to know the set of possibilities.  Implementation
1398  * is deferred.
1399  */
1400 static void
1401 mccase(struct parse *p, cset *cs)
1402 {
1403         assert(cs->multis == NULL);     /* xxx */
1404 }
1405
1406 /*
1407  - isinsets - is this character in any sets?
1408  == static int isinsets(struct re_guts *g, int c);
1409  */
1410 static int                      /* predicate */
1411 isinsets(struct re_guts *g, int c)
1412 {
1413         uch *col;
1414         int i;
1415         int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1416         unsigned uc = (uch)c;
1417
1418         for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1419                 if (col[uc] != 0)
1420                         return(1);
1421         return(0);
1422 }
1423
1424 /*
1425  - samesets - are these two characters in exactly the same sets?
1426  == static int samesets(struct re_guts *g, int c1, int c2);
1427  */
1428 static int                      /* predicate */
1429 samesets(struct re_guts *g, int c1, int c2)
1430 {
1431         uch *col;
1432         int i;
1433         int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1434         unsigned uc1 = (uch)c1;
1435         unsigned uc2 = (uch)c2;
1436
1437         for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1438                 if (col[uc1] != col[uc2])
1439                         return(0);
1440         return(1);
1441 }
1442
1443 /*
1444  - categorize - sort out character categories
1445  == static void categorize(struct parse *p, struct re_guts *g);
1446  */
1447 static void
1448 categorize(struct parse *p, struct re_guts *g)
1449 {
1450         cat_t *cats = g->categories;
1451         int c;
1452         int c2;
1453         cat_t cat;
1454
1455         /* avoid making error situations worse */
1456         if (p->error != 0)
1457                 return;
1458
1459         for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1460                 if (cats[c] == 0 && isinsets(g, c)) {
1461                         cat = g->ncategories++;
1462                         cats[c] = cat;
1463                         for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1464                                 if (cats[c2] == 0 && samesets(g, c, c2))
1465                                         cats[c2] = cat;
1466                 }
1467 }
1468
1469 /*
1470  - dupl - emit a duplicate of a bunch of sops
1471  == static sopno dupl(struct parse *p, sopno start, sopno finish);
1472  */
1473 static sopno                    /* start of duplicate */
1474 dupl(struct parse *p,
1475      sopno start,               /* from here */
1476      sopno finish)              /* to this less one */
1477 {
1478         sopno ret = HERE();
1479         sopno len = finish - start;
1480
1481         assert(finish >= start);
1482         if (len == 0)
1483                 return(ret);
1484         enlarge(p, p->ssize + len);     /* this many unexpected additions */
1485         assert(p->ssize >= p->slen + len);
1486         (void) memcpy((char *)(p->strip + p->slen),
1487                 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1488         p->slen += len;
1489         return(ret);
1490 }
1491
1492 /*
1493  - doemit - emit a strip operator
1494  == static void doemit(struct parse *p, sop op, size_t opnd);
1495  *
1496  * It might seem better to implement this as a macro with a function as
1497  * hard-case backup, but it's just too big and messy unless there are
1498  * some changes to the data structures.  Maybe later.
1499  */
1500 static void
1501 doemit(struct parse *p, sop op, size_t opnd)
1502 {
1503         /* avoid making error situations worse */
1504         if (p->error != 0)
1505                 return;
1506
1507         /* deal with oversize operands ("can't happen", more or less) */
1508         assert(opnd < 1<<OPSHIFT);
1509
1510         /* deal with undersized strip */
1511         if (p->slen >= p->ssize)
1512                 enlarge(p, (p->ssize+1) / 2 * 3);       /* +50% */
1513         assert(p->slen < p->ssize);
1514
1515         /* finally, it's all reduced to the easy case */
1516         p->strip[p->slen++] = SOP(op, opnd);
1517 }
1518
1519 /*
1520  - doinsert - insert a sop into the strip
1521  == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1522  */
1523 static void
1524 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1525 {
1526         sopno sn;
1527         sop s;
1528         int i;
1529
1530         /* avoid making error situations worse */
1531         if (p->error != 0)
1532                 return;
1533
1534         sn = HERE();
1535         EMIT(op, opnd);         /* do checks, ensure space */
1536         assert(HERE() == sn+1);
1537         s = p->strip[sn];
1538
1539         /* adjust paren pointers */
1540         assert(pos > 0);
1541         for (i = 1; i < NPAREN; i++) {
1542                 if (p->pbegin[i] >= pos) {
1543                         p->pbegin[i]++;
1544                 }
1545                 if (p->pend[i] >= pos) {
1546                         p->pend[i]++;
1547                 }
1548         }
1549
1550         memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1551                                                 (HERE()-pos-1)*sizeof(sop));
1552         p->strip[pos] = s;
1553 }
1554
1555 /*
1556  - dofwd - complete a forward reference
1557  == static void dofwd(struct parse *p, sopno pos, sop value);
1558  */
1559 static void
1560 dofwd(struct parse *p, sopno pos, sop value)
1561 {
1562         /* avoid making error situations worse */
1563         if (p->error != 0)
1564                 return;
1565
1566         assert(value < 1<<OPSHIFT);
1567         p->strip[pos] = OP(p->strip[pos]) | value;
1568 }
1569
1570 /*
1571  - enlarge - enlarge the strip
1572  == static void enlarge(struct parse *p, sopno size);
1573  */
1574 static void
1575 enlarge(struct parse *p, sopno size)
1576 {
1577         sop *sp;
1578
1579         if (p->ssize >= size)
1580                 return;
1581
1582         sp = (sop *)realloc(p->strip, size*sizeof(sop));
1583         if (sp == NULL) {
1584                 SETERROR(REG_ESPACE);
1585                 return;
1586         }
1587         p->strip = sp;
1588         p->ssize = size;
1589 }
1590
1591 /*
1592  - stripsnug - compact the strip
1593  == static void stripsnug(struct parse *p, struct re_guts *g);
1594  */
1595 static void
1596 stripsnug(struct parse *p, struct re_guts *g)
1597 {
1598         g->nstates = p->slen;
1599         g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1600         if (g->strip == NULL) {
1601                 SETERROR(REG_ESPACE);
1602                 g->strip = p->strip;
1603         }
1604 }
1605
1606 /*
1607  - findmust - fill in must and mlen with longest mandatory literal string
1608  == static void findmust(struct parse *p, struct re_guts *g);
1609  *
1610  * This algorithm could do fancy things like analyzing the operands of |
1611  * for common subsequences.  Someday.  This code is simple and finds most
1612  * of the interesting cases.
1613  *
1614  * Note that must and mlen got initialized during setup.
1615  */
1616 static void
1617 findmust(struct parse *p, struct re_guts *g)
1618 {
1619         sop *scan;
1620         sop *start;
1621         sop *newstart;
1622         sopno newlen;
1623         sop s;
1624         char *cp;
1625         sopno i;
1626         int offset;
1627         int cs, mccs;
1628
1629         /* avoid making error situations worse */
1630         if (p->error != 0)
1631                 return;
1632
1633         /* Find out if we can handle OANYOF or not */
1634         mccs = 0;
1635         for (cs = 0; cs < g->ncsets; cs++)
1636                 if (g->sets[cs].multis != NULL)
1637                         mccs = 1;
1638
1639         /* find the longest OCHAR sequence in strip */
1640         newlen = 0;
1641         offset = 0;
1642         g->moffset = 0;
1643         scan = g->strip + 1;
1644         do {
1645                 s = *scan++;
1646                 switch (OP(s)) {
1647                 case OCHAR:             /* sequence member */
1648                         if (newlen == 0)                /* new sequence */
1649                                 newstart = scan - 1;
1650                         newlen++;
1651                         break;
1652                 case OPLUS_:            /* things that don't break one */
1653                 case OLPAREN:
1654                 case ORPAREN:
1655                         break;
1656                 case OQUEST_:           /* things that must be skipped */
1657                 case OCH_:
1658                         offset = altoffset(scan, offset, mccs);
1659                         scan--;
1660                         do {
1661                                 scan += OPND(s);
1662                                 s = *scan;
1663                                 /* assert() interferes w debug printouts */
1664                                 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1665                                                         OP(s) != OOR2) {
1666                                         g->iflags |= BAD;
1667                                         return;
1668                                 }
1669                         } while (OP(s) != O_QUEST && OP(s) != O_CH);
1670                         /* fallthrough */
1671                 case OBOW:              /* things that break a sequence */
1672                 case OEOW:
1673                 case OBOL:
1674                 case OEOL:
1675                 case O_QUEST:
1676                 case O_CH:
1677                 case OEND:
1678                         if (newlen > g->mlen) {         /* ends one */
1679                                 start = newstart;
1680                                 g->mlen = newlen;
1681                                 if (offset > -1) {
1682                                         g->moffset += offset;
1683                                         offset = newlen;
1684                                 } else
1685                                         g->moffset = offset;
1686                         } else {
1687                                 if (offset > -1)
1688                                         offset += newlen;
1689                         }
1690                         newlen = 0;
1691                         break;
1692                 case OANY:
1693                         if (newlen > g->mlen) {         /* ends one */
1694                                 start = newstart;
1695                                 g->mlen = newlen;
1696                                 if (offset > -1) {
1697                                         g->moffset += offset;
1698                                         offset = newlen;
1699                                 } else
1700                                         g->moffset = offset;
1701                         } else {
1702                                 if (offset > -1)
1703                                         offset += newlen;
1704                         }
1705                         if (offset > -1)
1706                                 offset++;
1707                         newlen = 0;
1708                         break;
1709                 case OANYOF:            /* may or may not invalidate offset */
1710                         /* First, everything as OANY */
1711                         if (newlen > g->mlen) {         /* ends one */
1712                                 start = newstart;
1713                                 g->mlen = newlen;
1714                                 if (offset > -1) {
1715                                         g->moffset += offset;
1716                                         offset = newlen;
1717                                 } else
1718                                         g->moffset = offset;
1719                         } else {
1720                                 if (offset > -1)
1721                                         offset += newlen;
1722                         }
1723                         if (offset > -1)
1724                                 offset++;
1725                         newlen = 0;
1726                         /* And, now, if we found out we can't deal with
1727                          * it, make offset = -1.
1728                          */
1729                         if (mccs)
1730                                 offset = -1;
1731                         break;
1732                 default:
1733                         /* Anything here makes it impossible or too hard
1734                          * to calculate the offset -- so we give up;
1735                          * save the last known good offset, in case the
1736                          * must sequence doesn't occur later.
1737                          */
1738                         if (newlen > g->mlen) {         /* ends one */
1739                                 start = newstart;
1740                                 g->mlen = newlen;
1741                                 if (offset > -1)
1742                                         g->moffset += offset;
1743                                 else
1744                                         g->moffset = offset;
1745                         }
1746                         offset = -1;
1747                         newlen = 0;
1748                         break;
1749                 }
1750         } while (OP(s) != OEND);
1751
1752         if (g->mlen == 0) {             /* there isn't one */
1753                 g->moffset = -1;
1754                 return;
1755         }
1756
1757         /* turn it into a character string */
1758         g->must = malloc((size_t)g->mlen + 1);
1759         if (g->must == NULL) {          /* argh; just forget it */
1760                 g->mlen = 0;
1761                 g->moffset = -1;
1762                 return;
1763         }
1764         cp = g->must;
1765         scan = start;
1766         for (i = g->mlen; i > 0; i--) {
1767                 while (OP(s = *scan++) != OCHAR)
1768                         continue;
1769                 assert(cp < g->must + g->mlen);
1770                 *cp++ = (char)OPND(s);
1771         }
1772         assert(cp == g->must + g->mlen);
1773         *cp++ = '\0';           /* just on general principles */
1774 }
1775
1776 /*
1777  - altoffset - choose biggest offset among multiple choices
1778  == static int altoffset(sop *scan, int offset, int mccs);
1779  *
1780  * Compute, recursively if necessary, the largest offset among multiple
1781  * re paths.
1782  */
1783 static int
1784 altoffset(sop *scan, int offset, int mccs)
1785 {
1786         int largest;
1787         int try;
1788         sop s;
1789
1790         /* If we gave up already on offsets, return */
1791         if (offset == -1)
1792                 return -1;
1793
1794         largest = 0;
1795         try = 0;
1796         s = *scan++;
1797         while (OP(s) != O_QUEST && OP(s) != O_CH) {
1798                 switch (OP(s)) {
1799                 case OOR1:
1800                         if (try > largest)
1801                                 largest = try;
1802                         try = 0;
1803                         break;
1804                 case OQUEST_:
1805                 case OCH_:
1806                         try = altoffset(scan, try, mccs);
1807                         if (try == -1)
1808                                 return -1;
1809                         scan--;
1810                         do {
1811                                 scan += OPND(s);
1812                                 s = *scan;
1813                                 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1814                                                         OP(s) != OOR2)
1815                                         return -1;
1816                         } while (OP(s) != O_QUEST && OP(s) != O_CH);
1817                         /* We must skip to the next position, or we'll
1818                          * leave altoffset() too early.
1819                          */
1820                         scan++;
1821                         break;
1822                 case OANYOF:
1823                         if (mccs)
1824                                 return -1;
1825                 case OCHAR:
1826                 case OANY:
1827                         try++;
1828                 case OBOW:
1829                 case OEOW:
1830                 case OLPAREN:
1831                 case ORPAREN:
1832                 case OOR2:
1833                         break;
1834                 default:
1835                         try = -1;
1836                         break;
1837                 }
1838                 if (try == -1)
1839                         return -1;
1840                 s = *scan++;
1841         }
1842
1843         if (try > largest)
1844                 largest = try;
1845
1846         return largest+offset;
1847 }
1848
1849 /*
1850  - computejumps - compute char jumps for BM scan
1851  == static void computejumps(struct parse *p, struct re_guts *g);
1852  *
1853  * This algorithm assumes g->must exists and is has size greater than
1854  * zero. It's based on the algorithm found on Computer Algorithms by
1855  * Sara Baase.
1856  *
1857  * A char jump is the number of characters one needs to jump based on
1858  * the value of the character from the text that was mismatched.
1859  */
1860 static void
1861 computejumps(struct parse *p, struct re_guts *g)
1862 {
1863         int ch;
1864         int mindex;
1865
1866         /* Avoid making errors worse */
1867         if (p->error != 0)
1868                 return;
1869
1870         g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1871         if (g->charjump == NULL)        /* Not a fatal error */
1872                 return;
1873         /* Adjust for signed chars, if necessary */
1874         g->charjump = &g->charjump[-(CHAR_MIN)];
1875
1876         /* If the character does not exist in the pattern, the jump
1877          * is equal to the number of characters in the pattern.
1878          */
1879         for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1880                 g->charjump[ch] = g->mlen;
1881
1882         /* If the character does exist, compute the jump that would
1883          * take us to the last character in the pattern equal to it
1884          * (notice that we match right to left, so that last character
1885          * is the first one that would be matched).
1886          */
1887         for (mindex = 0; mindex < g->mlen; mindex++)
1888                 g->charjump[g->must[mindex]] = g->mlen - mindex - 1;
1889 }
1890
1891 /*
1892  - computematchjumps - compute match jumps for BM scan
1893  == static void computematchjumps(struct parse *p, struct re_guts *g);
1894  *
1895  * This algorithm assumes g->must exists and is has size greater than
1896  * zero. It's based on the algorithm found on Computer Algorithms by
1897  * Sara Baase.
1898  *
1899  * A match jump is the number of characters one needs to advance based
1900  * on the already-matched suffix.
1901  * Notice that all values here are minus (g->mlen-1), because of the way
1902  * the search algorithm works.
1903  */
1904 static void
1905 computematchjumps(struct parse *p, struct re_guts *g)
1906 {
1907         int mindex;             /* General "must" iterator */
1908         int suffix;             /* Keeps track of matching suffix */
1909         int ssuffix;            /* Keeps track of suffixes' suffix */
1910         int* pmatches;          /* pmatches[k] points to the next i
1911                                  * such that i+1...mlen is a substring
1912                                  * of k+1...k+mlen-i-1
1913                                  */
1914
1915         /* Avoid making errors worse */
1916         if (p->error != 0)
1917                 return;
1918
1919         pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1920         if (pmatches == NULL) {
1921                 g->matchjump = NULL;
1922                 return;
1923         }
1924
1925         g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1926         if (g->matchjump == NULL)       /* Not a fatal error */
1927                 return;
1928
1929         /* Set maximum possible jump for each character in the pattern */
1930         for (mindex = 0; mindex < g->mlen; mindex++)
1931                 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1932
1933         /* Compute pmatches[] */
1934         for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1935             mindex--, suffix--) {
1936                 pmatches[mindex] = suffix;
1937
1938                 /* If a mismatch is found, interrupting the substring,
1939                  * compute the matchjump for that position. If no
1940                  * mismatch is found, then a text substring mismatched
1941                  * against the suffix will also mismatch against the
1942                  * substring.
1943                  */
1944                 while (suffix < g->mlen
1945                     && g->must[mindex] != g->must[suffix]) {
1946                         g->matchjump[suffix] = MIN(g->matchjump[suffix],
1947                             g->mlen - mindex - 1);
1948                         suffix = pmatches[suffix];
1949                 }
1950         }
1951
1952         /* Compute the matchjump up to the last substring found to jump
1953          * to the beginning of the largest must pattern prefix matching
1954          * it's own suffix.
1955          */
1956         for (mindex = 0; mindex <= suffix; mindex++)
1957                 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1958                     g->mlen + suffix - mindex);
1959
1960         ssuffix = pmatches[suffix];
1961         while (suffix < g->mlen) {
1962                 while (suffix <= ssuffix && suffix < g->mlen) {
1963                         g->matchjump[suffix] = MIN(g->matchjump[suffix],
1964                             g->mlen + ssuffix - suffix);
1965                         suffix++;
1966                 }
1967                 if (suffix < g->mlen)
1968                         ssuffix = pmatches[ssuffix];
1969         }
1970
1971         free(pmatches);
1972 }
1973
1974 /*
1975  - pluscount - count + nesting
1976  == static sopno pluscount(struct parse *p, struct re_guts *g);
1977  */
1978 static sopno                    /* nesting depth */
1979 pluscount(struct parse *p, struct re_guts *g)
1980 {
1981         sop *scan;
1982         sop s;
1983         sopno plusnest = 0;
1984         sopno maxnest = 0;
1985
1986         if (p->error != 0)
1987                 return(0);      /* there may not be an OEND */
1988
1989         scan = g->strip + 1;
1990         do {
1991                 s = *scan++;
1992                 switch (OP(s)) {
1993                 case OPLUS_:
1994                         plusnest++;
1995                         break;
1996                 case O_PLUS:
1997                         if (plusnest > maxnest)
1998                                 maxnest = plusnest;
1999                         plusnest--;
2000                         break;
2001                 }
2002         } while (OP(s) != OEND);
2003         if (plusnest != 0)
2004                 g->iflags |= BAD;
2005         return(maxnest);
2006 }