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