Cleanup:
[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.6 2005/11/13 02:17:18 swildner 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         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                 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                 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                 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                 REQUIRE(MORE(), REG_EESCAPE);
422                 c = GETNEXT();
423                 ordinary(p, c);
424                 break;
425         case '{':               /* okay as ordinary except if digit follows */
426                 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         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                                 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                         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         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         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                 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                 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                         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                 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                                 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                         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         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         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                 REQUIRE(MORE(), REG_EBRACK);
786                 c = PEEK();
787                 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
788                 p_b_cclass(p, cs);
789                 REQUIRE(MORE(), REG_EBRACK);
790                 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
791                 break;
792         case '=':               /* equivalence class */
793                 NEXT2();
794                 REQUIRE(MORE(), REG_EBRACK);
795                 c = PEEK();
796                 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
797                 p_b_eclass(p, cs);
798                 REQUIRE(MORE(), REG_EBRACK);
799                 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                                 REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
818                                 for (i = (uch)start; i <= (uch)finish; i++)
819                                         CHadd(cs, i);
820                         } else {
821                                 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         REQUIRE(MORE(), REG_EBRACK);
951         if (!EATTWO('[', '.'))
952                 return(GETNEXT());
953
954         /* collating symbol */
955         value = p_b_coll_elem(p, '.');
956         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                         memset((char *)p->g->setbits + (nbytes - css), 0, css);
1194                 else {
1195                         no = 0;
1196                         SETERROR(REG_ESPACE);
1197                         /* caller's responsibility not to do set ops */
1198                 }
1199         }
1200
1201         assert(p->g->sets != NULL);     /* xxx */
1202         cs = &p->g->sets[no];
1203         cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1204         cs->mask = 1 << ((no) % CHAR_BIT);
1205         cs->hash = 0;
1206         cs->smultis = 0;
1207         cs->multis = NULL;
1208
1209         return(cs);
1210 }
1211
1212 /*
1213  - freeset - free a now-unused set
1214  == static void freeset(struct parse *p, cset *cs);
1215  */
1216 static void
1217 freeset(struct parse *p, cset *cs)
1218 {
1219         int i;
1220         cset *top = &p->g->sets[p->g->ncsets];
1221         size_t css = (size_t)p->g->csetsize;
1222
1223         for (i = 0; i < css; i++)
1224                 CHsub(cs, i);
1225         if (cs == top-1)        /* recover only the easy case */
1226                 p->g->ncsets--;
1227 }
1228
1229 /*
1230  - freezeset - final processing on a set of characters
1231  == static int freezeset(struct parse *p, cset *cs);
1232  *
1233  * The main task here is merging identical sets.  This is usually a waste
1234  * of time (although the hash code minimizes the overhead), but can win
1235  * big if REG_ICASE is being used.  REG_ICASE, by the way, is why the hash
1236  * is done using addition rather than xor -- all ASCII [aA] sets xor to
1237  * the same value!
1238  */
1239 static int                      /* set number */
1240 freezeset(struct parse *p, cset *cs)
1241 {
1242         short h = cs->hash;
1243         int i;
1244         cset *top = &p->g->sets[p->g->ncsets];
1245         cset *cs2;
1246         size_t css = (size_t)p->g->csetsize;
1247
1248         /* look for an earlier one which is the same */
1249         for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1250                 if (cs2->hash == h && cs2 != cs) {
1251                         /* maybe */
1252                         for (i = 0; i < css; i++)
1253                                 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1254                                         break;          /* no */
1255                         if (i == css)
1256                                 break;                  /* yes */
1257                 }
1258
1259         if (cs2 < top) {        /* found one */
1260                 freeset(p, cs);
1261                 cs = cs2;
1262         }
1263
1264         return((int)(cs - p->g->sets));
1265 }
1266
1267 /*
1268  - firstch - return first character in a set (which must have at least one)
1269  == static int firstch(struct parse *p, cset *cs);
1270  */
1271 static int                      /* character; there is no "none" value */
1272 firstch(struct parse *p, cset *cs)
1273 {
1274         int i;
1275         size_t css = (size_t)p->g->csetsize;
1276
1277         for (i = 0; i < css; i++)
1278                 if (CHIN(cs, i))
1279                         return((char)i);
1280         assert(never);
1281         return(0);              /* arbitrary */
1282 }
1283
1284 /*
1285  - nch - number of characters in a set
1286  == static int nch(struct parse *p, cset *cs);
1287  */
1288 static int
1289 nch(struct parse *p, cset *cs)
1290 {
1291         int i;
1292         size_t css = (size_t)p->g->csetsize;
1293         int n = 0;
1294
1295         for (i = 0; i < css; i++)
1296                 if (CHIN(cs, i))
1297                         n++;
1298         return(n);
1299 }
1300
1301 /*
1302  - mcadd - add a collating element to a cset
1303  == static void mcadd(struct parse *p, cset *cs, \
1304  ==     char *cp);
1305  */
1306 static void
1307 mcadd(struct parse *p, cset *cs, char *cp)
1308 {
1309         size_t oldend = cs->smultis;
1310
1311         cs->smultis += strlen(cp) + 1;
1312         if (cs->multis == NULL)
1313                 cs->multis = malloc(cs->smultis);
1314         else
1315                 cs->multis = reallocf(cs->multis, cs->smultis);
1316         if (cs->multis == NULL) {
1317                 SETERROR(REG_ESPACE);
1318                 return;
1319         }
1320
1321         strcpy(cs->multis + oldend - 1, cp);
1322         cs->multis[cs->smultis - 1] = '\0';
1323 }
1324
1325 #if used
1326 /*
1327  - mcsub - subtract a collating element from a cset
1328  == static void mcsub(cset *cs, char *cp);
1329  */
1330 static void
1331 mcsub(cset *cs, char *cp)
1332 {
1333         char *fp = mcfind(cs, cp);
1334         size_t len = strlen(fp);
1335
1336         assert(fp != NULL);
1337         memmove(fp, fp + len + 1, cs->smultis - (fp + len + 1 - cs->multis));
1338         cs->smultis -= len;
1339
1340         if (cs->smultis == 0) {
1341                 free(cs->multis);
1342                 cs->multis = NULL;
1343                 return;
1344         }
1345
1346         cs->multis = reallocf(cs->multis, cs->smultis);
1347         assert(cs->multis != NULL);
1348 }
1349
1350 /*
1351  - mcin - is a collating element in a cset?
1352  == static int mcin(cset *cs, char *cp);
1353  */
1354 static int
1355 mcin(cset *cs, char *cp)
1356 {
1357         return(mcfind(cs, cp) != NULL);
1358 }
1359
1360 /*
1361  - mcfind - find a collating element in a cset
1362  == static char *mcfind(cset *cs, char *cp);
1363  */
1364 static char *
1365 mcfind(cset *cs, char *cp)
1366 {
1367         char *p;
1368
1369         if (cs->multis == NULL)
1370                 return(NULL);
1371         for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
1372                 if (strcmp(cp, p) == 0)
1373                         return(p);
1374         return(NULL);
1375 }
1376 #endif
1377
1378 /*
1379  - mcinvert - invert the list of collating elements in a cset
1380  == static void mcinvert(struct parse *p, cset *cs);
1381  *
1382  * This would have to know the set of possibilities.  Implementation
1383  * is deferred.
1384  */
1385 static void
1386 mcinvert(struct parse *p, cset *cs)
1387 {
1388         assert(cs->multis == NULL);     /* xxx */
1389 }
1390
1391 /*
1392  - mccase - add case counterparts of the list of collating elements in a cset
1393  == static void mccase(struct parse *p, cset *cs);
1394  *
1395  * This would have to know the set of possibilities.  Implementation
1396  * is deferred.
1397  */
1398 static void
1399 mccase(struct parse *p, cset *cs)
1400 {
1401         assert(cs->multis == NULL);     /* xxx */
1402 }
1403
1404 /*
1405  - isinsets - is this character in any sets?
1406  == static int isinsets(struct re_guts *g, int c);
1407  */
1408 static int                      /* predicate */
1409 isinsets(struct re_guts *g, int c)
1410 {
1411         uch *col;
1412         int i;
1413         int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1414         unsigned uc = (uch)c;
1415
1416         for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1417                 if (col[uc] != 0)
1418                         return(1);
1419         return(0);
1420 }
1421
1422 /*
1423  - samesets - are these two characters in exactly the same sets?
1424  == static int samesets(struct re_guts *g, int c1, int c2);
1425  */
1426 static int                      /* predicate */
1427 samesets(struct re_guts *g, int c1, int c2)
1428 {
1429         uch *col;
1430         int i;
1431         int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1432         unsigned uc1 = (uch)c1;
1433         unsigned uc2 = (uch)c2;
1434
1435         for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1436                 if (col[uc1] != col[uc2])
1437                         return(0);
1438         return(1);
1439 }
1440
1441 /*
1442  - categorize - sort out character categories
1443  == static void categorize(struct parse *p, struct re_guts *g);
1444  */
1445 static void
1446 categorize(struct parse *p, struct re_guts *g)
1447 {
1448         cat_t *cats = g->categories;
1449         int c;
1450         int c2;
1451         cat_t cat;
1452
1453         /* avoid making error situations worse */
1454         if (p->error != 0)
1455                 return;
1456
1457         for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1458                 if (cats[c] == 0 && isinsets(g, c)) {
1459                         cat = g->ncategories++;
1460                         cats[c] = cat;
1461                         for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1462                                 if (cats[c2] == 0 && samesets(g, c, c2))
1463                                         cats[c2] = cat;
1464                 }
1465 }
1466
1467 /*
1468  - dupl - emit a duplicate of a bunch of sops
1469  == static sopno dupl(struct parse *p, sopno start, sopno finish);
1470  */
1471 static sopno                    /* start of duplicate */
1472 dupl(struct parse *p,
1473      sopno start,               /* from here */
1474      sopno finish)              /* to this less one */
1475 {
1476         sopno ret = HERE();
1477         sopno len = finish - start;
1478
1479         assert(finish >= start);
1480         if (len == 0)
1481                 return(ret);
1482         enlarge(p, p->ssize + len);     /* this many unexpected additions */
1483         assert(p->ssize >= p->slen + len);
1484         memcpy((char *)(p->strip + p->slen), (char *)(p->strip + start),
1485                (size_t)len*sizeof(sop));
1486         p->slen += len;
1487         return(ret);
1488 }
1489
1490 /*
1491  - doemit - emit a strip operator
1492  == static void doemit(struct parse *p, sop op, size_t opnd);
1493  *
1494  * It might seem better to implement this as a macro with a function as
1495  * hard-case backup, but it's just too big and messy unless there are
1496  * some changes to the data structures.  Maybe later.
1497  */
1498 static void
1499 doemit(struct parse *p, sop op, size_t opnd)
1500 {
1501         /* avoid making error situations worse */
1502         if (p->error != 0)
1503                 return;
1504
1505         /* deal with oversize operands ("can't happen", more or less) */
1506         assert(opnd < 1<<OPSHIFT);
1507
1508         /* deal with undersized strip */
1509         if (p->slen >= p->ssize)
1510                 enlarge(p, (p->ssize+1) / 2 * 3);       /* +50% */
1511         assert(p->slen < p->ssize);
1512
1513         /* finally, it's all reduced to the easy case */
1514         p->strip[p->slen++] = SOP(op, opnd);
1515 }
1516
1517 /*
1518  - doinsert - insert a sop into the strip
1519  == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1520  */
1521 static void
1522 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1523 {
1524         sopno sn;
1525         sop s;
1526         int i;
1527
1528         /* avoid making error situations worse */
1529         if (p->error != 0)
1530                 return;
1531
1532         sn = HERE();
1533         EMIT(op, opnd);         /* do checks, ensure space */
1534         assert(HERE() == sn+1);
1535         s = p->strip[sn];
1536
1537         /* adjust paren pointers */
1538         assert(pos > 0);
1539         for (i = 1; i < NPAREN; i++) {
1540                 if (p->pbegin[i] >= pos) {
1541                         p->pbegin[i]++;
1542                 }
1543                 if (p->pend[i] >= pos) {
1544                         p->pend[i]++;
1545                 }
1546         }
1547
1548         memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1549                                                 (HERE()-pos-1)*sizeof(sop));
1550         p->strip[pos] = s;
1551 }
1552
1553 /*
1554  - dofwd - complete a forward reference
1555  == static void dofwd(struct parse *p, sopno pos, sop value);
1556  */
1557 static void
1558 dofwd(struct parse *p, sopno pos, sop value)
1559 {
1560         /* avoid making error situations worse */
1561         if (p->error != 0)
1562                 return;
1563
1564         assert(value < 1<<OPSHIFT);
1565         p->strip[pos] = OP(p->strip[pos]) | value;
1566 }
1567
1568 /*
1569  - enlarge - enlarge the strip
1570  == static void enlarge(struct parse *p, sopno size);
1571  */
1572 static void
1573 enlarge(struct parse *p, sopno size)
1574 {
1575         sop *sp;
1576
1577         if (p->ssize >= size)
1578                 return;
1579
1580         sp = (sop *)realloc(p->strip, size*sizeof(sop));
1581         if (sp == NULL) {
1582                 SETERROR(REG_ESPACE);
1583                 return;
1584         }
1585         p->strip = sp;
1586         p->ssize = size;
1587 }
1588
1589 /*
1590  - stripsnug - compact the strip
1591  == static void stripsnug(struct parse *p, struct re_guts *g);
1592  */
1593 static void
1594 stripsnug(struct parse *p, struct re_guts *g)
1595 {
1596         g->nstates = p->slen;
1597         g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1598         if (g->strip == NULL) {
1599                 SETERROR(REG_ESPACE);
1600                 g->strip = p->strip;
1601         }
1602 }
1603
1604 /*
1605  - findmust - fill in must and mlen with longest mandatory literal string
1606  == static void findmust(struct parse *p, struct re_guts *g);
1607  *
1608  * This algorithm could do fancy things like analyzing the operands of |
1609  * for common subsequences.  Someday.  This code is simple and finds most
1610  * of the interesting cases.
1611  *
1612  * Note that must and mlen got initialized during setup.
1613  */
1614 static void
1615 findmust(struct parse *p, struct re_guts *g)
1616 {
1617         sop *scan;
1618         sop *start;
1619         sop *newstart;
1620         sopno newlen;
1621         sop s;
1622         char *cp;
1623         sopno i;
1624         int offset;
1625         int cs, mccs;
1626
1627         /* avoid making error situations worse */
1628         if (p->error != 0)
1629                 return;
1630
1631         /* Find out if we can handle OANYOF or not */
1632         mccs = 0;
1633         for (cs = 0; cs < g->ncsets; cs++)
1634                 if (g->sets[cs].multis != NULL)
1635                         mccs = 1;
1636
1637         /* find the longest OCHAR sequence in strip */
1638         newlen = 0;
1639         offset = 0;
1640         g->moffset = 0;
1641         scan = g->strip + 1;
1642         do {
1643                 s = *scan++;
1644                 switch (OP(s)) {
1645                 case OCHAR:             /* sequence member */
1646                         if (newlen == 0)                /* new sequence */
1647                                 newstart = scan - 1;
1648                         newlen++;
1649                         break;
1650                 case OPLUS_:            /* things that don't break one */
1651                 case OLPAREN:
1652                 case ORPAREN:
1653                         break;
1654                 case OQUEST_:           /* things that must be skipped */
1655                 case OCH_:
1656                         offset = altoffset(scan, offset, mccs);
1657                         scan--;
1658                         do {
1659                                 scan += OPND(s);
1660                                 s = *scan;
1661                                 /* assert() interferes w debug printouts */
1662                                 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1663                                                         OP(s) != OOR2) {
1664                                         g->iflags |= BAD;
1665                                         return;
1666                                 }
1667                         } while (OP(s) != O_QUEST && OP(s) != O_CH);
1668                         /* fallthrough */
1669                 case OBOW:              /* things that break a sequence */
1670                 case OEOW:
1671                 case OBOL:
1672                 case OEOL:
1673                 case O_QUEST:
1674                 case O_CH:
1675                 case OEND:
1676                         if (newlen > g->mlen) {         /* ends one */
1677                                 start = newstart;
1678                                 g->mlen = newlen;
1679                                 if (offset > -1) {
1680                                         g->moffset += offset;
1681                                         offset = newlen;
1682                                 } else
1683                                         g->moffset = offset;
1684                         } else {
1685                                 if (offset > -1)
1686                                         offset += newlen;
1687                         }
1688                         newlen = 0;
1689                         break;
1690                 case OANY:
1691                         if (newlen > g->mlen) {         /* ends one */
1692                                 start = newstart;
1693                                 g->mlen = newlen;
1694                                 if (offset > -1) {
1695                                         g->moffset += offset;
1696                                         offset = newlen;
1697                                 } else
1698                                         g->moffset = offset;
1699                         } else {
1700                                 if (offset > -1)
1701                                         offset += newlen;
1702                         }
1703                         if (offset > -1)
1704                                 offset++;
1705                         newlen = 0;
1706                         break;
1707                 case OANYOF:            /* may or may not invalidate offset */
1708                         /* First, everything as OANY */
1709                         if (newlen > g->mlen) {         /* ends one */
1710                                 start = newstart;
1711                                 g->mlen = newlen;
1712                                 if (offset > -1) {
1713                                         g->moffset += offset;
1714                                         offset = newlen;
1715                                 } else
1716                                         g->moffset = offset;
1717                         } else {
1718                                 if (offset > -1)
1719                                         offset += newlen;
1720                         }
1721                         if (offset > -1)
1722                                 offset++;
1723                         newlen = 0;
1724                         /* And, now, if we found out we can't deal with
1725                          * it, make offset = -1.
1726                          */
1727                         if (mccs)
1728                                 offset = -1;
1729                         break;
1730                 default:
1731                         /* Anything here makes it impossible or too hard
1732                          * to calculate the offset -- so we give up;
1733                          * save the last known good offset, in case the
1734                          * must sequence doesn't occur later.
1735                          */
1736                         if (newlen > g->mlen) {         /* ends one */
1737                                 start = newstart;
1738                                 g->mlen = newlen;
1739                                 if (offset > -1)
1740                                         g->moffset += offset;
1741                                 else
1742                                         g->moffset = offset;
1743                         }
1744                         offset = -1;
1745                         newlen = 0;
1746                         break;
1747                 }
1748         } while (OP(s) != OEND);
1749
1750         if (g->mlen == 0) {             /* there isn't one */
1751                 g->moffset = -1;
1752                 return;
1753         }
1754
1755         /* turn it into a character string */
1756         g->must = malloc((size_t)g->mlen + 1);
1757         if (g->must == NULL) {          /* argh; just forget it */
1758                 g->mlen = 0;
1759                 g->moffset = -1;
1760                 return;
1761         }
1762         cp = g->must;
1763         scan = start;
1764         for (i = g->mlen; i > 0; i--) {
1765                 while (OP(s = *scan++) != OCHAR)
1766                         continue;
1767                 assert(cp < g->must + g->mlen);
1768                 *cp++ = (char)OPND(s);
1769         }
1770         assert(cp == g->must + g->mlen);
1771         *cp++ = '\0';           /* just on general principles */
1772 }
1773
1774 /*
1775  - altoffset - choose biggest offset among multiple choices
1776  == static int altoffset(sop *scan, int offset, int mccs);
1777  *
1778  * Compute, recursively if necessary, the largest offset among multiple
1779  * re paths.
1780  */
1781 static int
1782 altoffset(sop *scan, int offset, int mccs)
1783 {
1784         int largest;
1785         int try;
1786         sop s;
1787
1788         /* If we gave up already on offsets, return */
1789         if (offset == -1)
1790                 return -1;
1791
1792         largest = 0;
1793         try = 0;
1794         s = *scan++;
1795         while (OP(s) != O_QUEST && OP(s) != O_CH) {
1796                 switch (OP(s)) {
1797                 case OOR1:
1798                         if (try > largest)
1799                                 largest = try;
1800                         try = 0;
1801                         break;
1802                 case OQUEST_:
1803                 case OCH_:
1804                         try = altoffset(scan, try, mccs);
1805                         if (try == -1)
1806                                 return -1;
1807                         scan--;
1808                         do {
1809                                 scan += OPND(s);
1810                                 s = *scan;
1811                                 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1812                                                         OP(s) != OOR2)
1813                                         return -1;
1814                         } while (OP(s) != O_QUEST && OP(s) != O_CH);
1815                         /* We must skip to the next position, or we'll
1816                          * leave altoffset() too early.
1817                          */
1818                         scan++;
1819                         break;
1820                 case OANYOF:
1821                         if (mccs)
1822                                 return -1;
1823                 case OCHAR:
1824                 case OANY:
1825                         try++;
1826                 case OBOW:
1827                 case OEOW:
1828                 case OLPAREN:
1829                 case ORPAREN:
1830                 case OOR2:
1831                         break;
1832                 default:
1833                         try = -1;
1834                         break;
1835                 }
1836                 if (try == -1)
1837                         return -1;
1838                 s = *scan++;
1839         }
1840
1841         if (try > largest)
1842                 largest = try;
1843
1844         return largest+offset;
1845 }
1846
1847 /*
1848  - computejumps - compute char jumps for BM scan
1849  == static void computejumps(struct parse *p, struct re_guts *g);
1850  *
1851  * This algorithm assumes g->must exists and is has size greater than
1852  * zero. It's based on the algorithm found on Computer Algorithms by
1853  * Sara Baase.
1854  *
1855  * A char jump is the number of characters one needs to jump based on
1856  * the value of the character from the text that was mismatched.
1857  */
1858 static void
1859 computejumps(struct parse *p, struct re_guts *g)
1860 {
1861         int ch;
1862         int mindex;
1863
1864         /* Avoid making errors worse */
1865         if (p->error != 0)
1866                 return;
1867
1868         g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1869         if (g->charjump == NULL)        /* Not a fatal error */
1870                 return;
1871         /* Adjust for signed chars, if necessary */
1872         g->charjump = &g->charjump[-(CHAR_MIN)];
1873
1874         /* If the character does not exist in the pattern, the jump
1875          * is equal to the number of characters in the pattern.
1876          */
1877         for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1878                 g->charjump[ch] = g->mlen;
1879
1880         /* If the character does exist, compute the jump that would
1881          * take us to the last character in the pattern equal to it
1882          * (notice that we match right to left, so that last character
1883          * is the first one that would be matched).
1884          */
1885         for (mindex = 0; mindex < g->mlen; mindex++)
1886                 g->charjump[g->must[mindex]] = g->mlen - mindex - 1;
1887 }
1888
1889 /*
1890  - computematchjumps - compute match jumps for BM scan
1891  == static void computematchjumps(struct parse *p, struct re_guts *g);
1892  *
1893  * This algorithm assumes g->must exists and is has size greater than
1894  * zero. It's based on the algorithm found on Computer Algorithms by
1895  * Sara Baase.
1896  *
1897  * A match jump is the number of characters one needs to advance based
1898  * on the already-matched suffix.
1899  * Notice that all values here are minus (g->mlen-1), because of the way
1900  * the search algorithm works.
1901  */
1902 static void
1903 computematchjumps(struct parse *p, struct re_guts *g)
1904 {
1905         int mindex;             /* General "must" iterator */
1906         int suffix;             /* Keeps track of matching suffix */
1907         int ssuffix;            /* Keeps track of suffixes' suffix */
1908         int* pmatches;          /* pmatches[k] points to the next i
1909                                  * such that i+1...mlen is a substring
1910                                  * of k+1...k+mlen-i-1
1911                                  */
1912
1913         /* Avoid making errors worse */
1914         if (p->error != 0)
1915                 return;
1916
1917         pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1918         if (pmatches == NULL) {
1919                 g->matchjump = NULL;
1920                 return;
1921         }
1922
1923         g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1924         if (g->matchjump == NULL)       /* Not a fatal error */
1925                 return;
1926
1927         /* Set maximum possible jump for each character in the pattern */
1928         for (mindex = 0; mindex < g->mlen; mindex++)
1929                 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1930
1931         /* Compute pmatches[] */
1932         for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1933             mindex--, suffix--) {
1934                 pmatches[mindex] = suffix;
1935
1936                 /* If a mismatch is found, interrupting the substring,
1937                  * compute the matchjump for that position. If no
1938                  * mismatch is found, then a text substring mismatched
1939                  * against the suffix will also mismatch against the
1940                  * substring.
1941                  */
1942                 while (suffix < g->mlen
1943                     && g->must[mindex] != g->must[suffix]) {
1944                         g->matchjump[suffix] = MIN(g->matchjump[suffix],
1945                             g->mlen - mindex - 1);
1946                         suffix = pmatches[suffix];
1947                 }
1948         }
1949
1950         /* Compute the matchjump up to the last substring found to jump
1951          * to the beginning of the largest must pattern prefix matching
1952          * it's own suffix.
1953          */
1954         for (mindex = 0; mindex <= suffix; mindex++)
1955                 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1956                     g->mlen + suffix - mindex);
1957
1958         ssuffix = pmatches[suffix];
1959         while (suffix < g->mlen) {
1960                 while (suffix <= ssuffix && suffix < g->mlen) {
1961                         g->matchjump[suffix] = MIN(g->matchjump[suffix],
1962                             g->mlen + ssuffix - suffix);
1963                         suffix++;
1964                 }
1965                 if (suffix < g->mlen)
1966                         ssuffix = pmatches[ssuffix];
1967         }
1968
1969         free(pmatches);
1970 }
1971
1972 /*
1973  - pluscount - count + nesting
1974  == static sopno pluscount(struct parse *p, struct re_guts *g);
1975  */
1976 static sopno                    /* nesting depth */
1977 pluscount(struct parse *p, struct re_guts *g)
1978 {
1979         sop *scan;
1980         sop s;
1981         sopno plusnest = 0;
1982         sopno maxnest = 0;
1983
1984         if (p->error != 0)
1985                 return(0);      /* there may not be an OEND */
1986
1987         scan = g->strip + 1;
1988         do {
1989                 s = *scan++;
1990                 switch (OP(s)) {
1991                 case OPLUS_:
1992                         plusnest++;
1993                         break;
1994                 case O_PLUS:
1995                         if (plusnest > maxnest)
1996                                 maxnest = plusnest;
1997                         plusnest--;
1998                         break;
1999                 }
2000         } while (OP(s) != OEND);
2001         if (plusnest != 0)
2002                 g->iflags |= BAD;
2003         return(maxnest);
2004 }