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.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
33 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
36 #if defined(LIBC_SCCS) && !defined(lint)
37 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
38 #endif /* LIBC_SCCS and not lint */
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include <sys/types.h>
61 * parse structure, passed up and down to avoid global variables and
65 char *next; /* next character in RE */
66 char *end; /* end of string (-> NUL normally) */
67 int error; /* has an error been seen? */
68 sop *strip; /* malloced strip */
69 sopno ssize; /* malloced strip size (allocated) */
70 sopno slen; /* malloced strip length (used) */
71 int ncsalloc; /* number of csets allocated */
73 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
74 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
75 sopno pend[NPAREN]; /* -> ) ([0] unused) */
78 /* ========= begin header generated by ./mkh ========= */
83 /* === regcomp.c === */
84 static void p_ere(struct parse *p, wint_t stop);
85 static void p_ere_exp(struct parse *p);
86 static void p_str(struct parse *p);
87 static void p_bre(struct parse *p, wint_t end1, wint_t end2);
88 static int p_simp_re(struct parse *p, int starordinary);
89 static int p_count(struct parse *p);
90 static void p_bracket(struct parse *p);
91 static void p_b_term(struct parse *p, cset *cs);
92 static void p_b_cclass(struct parse *p, cset *cs);
93 static void p_b_eclass(struct parse *p, cset *cs);
94 static wint_t p_b_symbol(struct parse *p);
95 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
96 static wint_t othercase(wint_t ch);
97 static void bothcases(struct parse *p, wint_t ch);
98 static void ordinary(struct parse *p, wint_t ch);
99 static void nonnewline(struct parse *p);
100 static void repeat(struct parse *p, sopno start, int from, int to);
101 static int seterr(struct parse *p, int e);
102 static cset *allocset(struct parse *p);
103 static void freeset(struct parse *p, cset *cs);
104 static void CHadd(struct parse *p, cset *cs, wint_t ch);
105 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
106 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
107 static wint_t singleton(cset *cs);
108 static sopno dupl(struct parse *p, sopno start, sopno finish);
109 static void doemit(struct parse *p, sop op, size_t opnd);
110 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
111 static void dofwd(struct parse *p, sopno pos, sop value);
112 static void enlarge(struct parse *p, sopno size);
113 static void stripsnug(struct parse *p, struct re_guts *g);
114 static void findmust(struct parse *p, struct re_guts *g);
115 static int altoffset(sop *scan, int offset);
116 static void computejumps(struct parse *p, struct re_guts *g);
117 static void computematchjumps(struct parse *p, struct re_guts *g);
118 static sopno pluscount(struct parse *p, struct re_guts *g);
119 static wint_t wgetnext(struct parse *p);
124 /* ========= end header generated by ./mkh ========= */
126 static char nuls[10]; /* place to point scanner in event of error */
129 * macros for use with parse structure
130 * BEWARE: these know that the parse structure is named `p' !!!
132 #define PEEK() (*p->next)
133 #define PEEK2() (*(p->next+1))
134 #define MORE() (p->next < p->end)
135 #define MORE2() (p->next+1 < p->end)
136 #define SEE(c) (MORE() && PEEK() == (c))
137 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
138 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
139 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
140 #define NEXT() (p->next++)
141 #define NEXT2() (p->next += 2)
142 #define NEXTn(n) (p->next += (n))
143 #define GETNEXT() (*p->next++)
144 #define WGETNEXT() wgetnext(p)
145 #define SETERROR(e) seterr(p, (e))
146 #define REQUIRE(co, e) ((co) || SETERROR(e))
147 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
148 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
149 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
150 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
151 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
152 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
153 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
154 #define HERE() (p->slen)
155 #define THERE() (p->slen - 1)
156 #define THERETHERE() (p->slen - 2)
157 #define DROP(n) (p->slen -= (n))
160 static int never = 0; /* for use in asserts; shuts lint up */
162 #define never 0 /* some <assert.h>s have bugs too */
165 /* Macro used by computejump()/computematchjump() */
166 #define MIN(a,b) ((a)<(b)?(a):(b))
169 - regcomp - interface for parser and compilation
170 = extern int regcomp(regex_t *, const char *, int);
171 = #define REG_BASIC 0000
172 = #define REG_EXTENDED 0001
173 = #define REG_ICASE 0002
174 = #define REG_NOSUB 0004
175 = #define REG_NEWLINE 0010
176 = #define REG_NOSPEC 0020
177 = #define REG_PEND 0040
178 = #define REG_DUMP 0200
180 int /* 0 success, otherwise REG_something */
181 regcomp(regex_t * __restrict preg,
182 const char * __restrict pattern,
187 struct parse *p = &pa;
192 # define GOODFLAGS(f) (f)
194 # define GOODFLAGS(f) ((f)&~REG_DUMP)
197 cflags = GOODFLAGS(cflags);
198 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
201 if (cflags®_PEND) {
202 if (preg->re_endp < pattern)
204 len = preg->re_endp - pattern;
206 len = strlen((char *)pattern);
208 /* do the mallocs early so failure handling is easy */
209 g = (struct re_guts *)malloc(sizeof(struct re_guts));
213 * Limit the pattern space to avoid a 32-bit overflow on buffer
214 * extension. Also avoid any signed overflow in case of conversion
215 * so make the real limit based on a 31-bit overflow.
217 * Likely not applicable on 64-bit systems but handle the case
218 * generically (who are we to stop people from using ~715MB+
221 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
226 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
227 assert(p->ssize >= len);
229 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
231 if (p->strip == NULL) {
238 p->next = (char *)pattern; /* convenience; we do not modify it */
239 p->end = p->next + len;
242 for (i = 0; i < NPAREN; i++) {
262 g->firststate = THERE();
263 if (cflags®_EXTENDED)
265 else if (cflags®_NOSPEC)
270 g->laststate = THERE();
272 /* tidy up loose ends and fill things in */
275 /* only use Boyer-Moore algorithm if the pattern is bigger
276 * than three characters
280 computematchjumps(p, g);
281 if(g->matchjump == NULL && g->charjump != NULL) {
286 g->nplus = pluscount(p, g);
288 preg->re_nsub = g->nsub;
290 preg->re_magic = MAGIC1;
292 /* not debugging, so can't rely on the assert() in regexec() */
294 SETERROR(REG_ASSERT);
297 /* win or lose, we're done */
298 if (p->error != 0) /* lose */
304 - p_ere - ERE parser top level, concatenation and alternation
305 == static void p_ere(struct parse *p, int stop);
308 p_ere(struct parse *p,
309 int stop) /* character this ERE should end at */
315 int first = 1; /* is this the first alternative? */
318 /* do a bunch of concatenated expressions */
320 while (MORE() && (c = PEEK()) != '|' && c != stop)
322 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
325 break; /* NOTE BREAK OUT */
328 INSERT(OCH_, conc); /* offset is wrong */
333 ASTERN(OOR1, prevback);
335 AHEAD(prevfwd); /* fix previous offset */
337 EMIT(OOR2, 0); /* offset is very wrong */
340 if (!first) { /* tail-end fixups */
342 ASTERN(O_CH, prevback);
345 assert(!MORE() || SEE(stop));
349 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
350 == static void p_ere_exp(struct parse *p);
353 p_ere_exp(struct parse *p)
363 assert(MORE()); /* caller should have ensured this */
369 (void)REQUIRE(MORE(), REG_EPAREN);
373 p->pbegin[subno] = HERE();
374 EMIT(OLPAREN, subno);
377 if (subno < NPAREN) {
378 p->pend[subno] = HERE();
379 assert(p->pend[subno] != 0);
381 EMIT(ORPAREN, subno);
382 (void)MUSTEAT(')', REG_EPAREN);
384 #ifndef POSIX_MISTAKE
385 case ')': /* happens only if no current unmatched ( */
387 * You may ask, why the ifndef? Because I didn't notice
388 * this until slightly too late for 1003.2, and none of the
389 * other 1003.2 regular-expression reviewers noticed it at
390 * all. So an unmatched ) is legal POSIX, at least until
391 * we can get it fixed.
393 SETERROR(REG_EPAREN);
398 p->g->iflags |= USEBOL;
404 p->g->iflags |= USEEOL;
413 SETERROR(REG_BADRPT);
416 if (p->g->cflags®_NEWLINE)
425 (void)REQUIRE(MORE(), REG_EESCAPE);
429 case '{': /* okay as ordinary except if digit follows */
430 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
442 /* we call { a repetition if followed by a digit */
443 if (!( c == '*' || c == '+' || c == '?' ||
444 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
445 return; /* no repetition, we're done */
448 (void)REQUIRE(!wascaret, REG_BADRPT);
450 case '*': /* implemented as +? */
451 /* this case does not require the (y|) trick, noKLUDGE */
454 INSERT(OQUEST_, pos);
455 ASTERN(O_QUEST, pos);
462 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
463 INSERT(OCH_, pos); /* offset slightly wrong */
464 ASTERN(OOR1, pos); /* this one's right */
465 AHEAD(pos); /* fix the OCH_ */
466 EMIT(OOR2, 0); /* offset very wrong... */
467 AHEAD(THERE()); /* ...so fix it */
468 ASTERN(O_CH, THERETHERE());
473 if (isdigit((uch)PEEK())) {
475 (void)REQUIRE(count <= count2, REG_BADBR);
476 } else /* single number with comma */
478 } else /* just a single number */
480 repeat(p, pos, count, count2);
481 if (!EAT('}')) { /* error heuristics */
482 while (MORE() && PEEK() != '}')
484 (void)REQUIRE(MORE(), REG_EBRACE);
493 if (!( c == '*' || c == '+' || c == '?' ||
494 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
496 SETERROR(REG_BADRPT);
500 - p_str - string (no metacharacters) "parser"
501 == static void p_str(struct parse *p);
504 p_str(struct parse *p)
506 (void)REQUIRE(MORE(), REG_EMPTY);
508 ordinary(p, WGETNEXT());
512 - p_bre - BRE parser top level, anchoring and concatenation
513 == static void p_bre(struct parse *p, int end1, \
515 * Giving end1 as OUT essentially eliminates the end1/end2 check.
517 * This implementation is a bit of a kludge, in that a trailing $ is first
518 * taken as an ordinary character and then revised to be an anchor.
519 * The amount of lookahead needed to avoid this kludge is excessive.
522 p_bre(struct parse *p,
523 int end1, /* first terminating character */
524 int end2) /* second terminating character */
526 sopno start = HERE();
527 int first = 1; /* first subexpression? */
532 p->g->iflags |= USEBOL;
535 while (MORE() && !SEETWO(end1, end2)) {
536 wasdollar = p_simp_re(p, first);
539 if (wasdollar) { /* oops, that was a trailing anchor */
542 p->g->iflags |= USEEOL;
546 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
550 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
551 == static int p_simp_re(struct parse *p, int starordinary);
553 static int /* was the simple RE an unbackslashed $? */
554 p_simp_re(struct parse *p,
555 int starordinary) /* is a leading * an ordinary character? */
564 # define BACKSL (1<<CHAR_BIT)
566 pos = HERE(); /* repetion op, if any, covers from here */
568 assert(MORE()); /* caller should have ensured this */
571 (void)REQUIRE(MORE(), REG_EESCAPE);
572 c = BACKSL | GETNEXT();
576 if (p->g->cflags®_NEWLINE)
585 SETERROR(REG_BADRPT);
591 p->pbegin[subno] = HERE();
592 EMIT(OLPAREN, subno);
593 /* the MORE here is an error heuristic */
594 if (MORE() && !SEETWO('\\', ')'))
596 if (subno < NPAREN) {
597 p->pend[subno] = HERE();
598 assert(p->pend[subno] != 0);
600 EMIT(ORPAREN, subno);
601 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
603 case BACKSL|')': /* should not get here -- must be user */
605 SETERROR(REG_EPAREN);
616 i = (c&~BACKSL) - '0';
618 if (p->pend[i] != 0) {
619 assert(i <= p->g->nsub);
621 assert(p->pbegin[i] != 0);
622 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
623 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
624 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
627 SETERROR(REG_ESUBREG);
631 (void)REQUIRE(starordinary, REG_BADRPT);
640 if (EAT('*')) { /* implemented as +? */
641 /* this case does not require the (y|) trick, noKLUDGE */
644 INSERT(OQUEST_, pos);
645 ASTERN(O_QUEST, pos);
646 } else if (EATTWO('\\', '{')) {
649 if (MORE() && isdigit((uch)PEEK())) {
651 (void)REQUIRE(count <= count2, REG_BADBR);
652 } else /* single number with comma */
654 } else /* just a single number */
656 repeat(p, pos, count, count2);
657 if (!EATTWO('\\', '}')) { /* error heuristics */
658 while (MORE() && !SEETWO('\\', '}'))
660 (void)REQUIRE(MORE(), REG_EBRACE);
663 } else if (c == '$') /* $ (but not \$) ends it */
670 - p_count - parse a repetition count
671 == static int p_count(struct parse *p);
673 static int /* the value */
674 p_count(struct parse *p)
679 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
680 count = count*10 + (GETNEXT() - '0');
684 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
689 - p_bracket - parse a bracketed character list
690 == static void p_bracket(struct parse *p);
693 p_bracket(struct parse *p)
698 /* Dept of Truly Sickening Special-Case Kludges */
699 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
704 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
710 if ((cs = allocset(p)) == NULL)
713 if (p->g->cflags®_ICASE)
721 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
725 (void)MUSTEAT(']', REG_EBRACK);
727 if (p->error != 0) /* don't mess things up further */
730 if (cs->invert && p->g->cflags®_NEWLINE)
731 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
733 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
737 EMIT(OANYOF, (int)(cs - p->g->sets));
741 - p_b_term - parse one term of a bracketed character list
742 == static void p_b_term(struct parse *p, cset *cs);
745 p_b_term(struct parse *p, cset *cs)
748 wint_t start, finish;
751 /* classify what we've got */
752 switch ((MORE()) ? PEEK() : '\0') {
754 c = (MORE2()) ? PEEK2() : '\0';
757 SETERROR(REG_ERANGE);
758 return; /* NOTE RETURN */
766 case ':': /* character class */
768 (void)REQUIRE(MORE(), REG_EBRACK);
770 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
772 (void)REQUIRE(MORE(), REG_EBRACK);
773 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
775 case '=': /* equivalence class */
777 (void)REQUIRE(MORE(), REG_EBRACK);
779 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
781 (void)REQUIRE(MORE(), REG_EBRACK);
782 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
784 default: /* symbol, ordinary character, or range */
785 start = p_b_symbol(p);
786 if (SEE('-') && MORE2() && PEEK2() != ']') {
792 finish = p_b_symbol(p);
798 if (__collate_load_error) {
799 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
800 CHaddrange(p, cs, start, finish);
802 (void)REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE);
803 for (i = 0; i <= UCHAR_MAX; i++) {
804 if ( __collate_range_cmp(start, i) <= 0
805 && __collate_range_cmp(i, finish) <= 0
816 - p_b_cclass - parse a character-class name and deal with it
817 == static void p_b_cclass(struct parse *p, cset *cs);
820 p_b_cclass(struct parse *p, cset *cs)
827 while (MORE() && isalpha((uch)PEEK()))
830 if (len >= sizeof(clname) - 1) {
831 SETERROR(REG_ECTYPE);
834 memcpy(clname, sp, len);
836 if ((wct = wctype(clname)) == 0) {
837 SETERROR(REG_ECTYPE);
840 CHaddtype(p, cs, wct);
844 - p_b_eclass - parse an equivalence-class name and deal with it
845 == static void p_b_eclass(struct parse *p, cset *cs);
847 * This implementation is incomplete. xxx
850 p_b_eclass(struct parse *p, cset *cs)
854 c = p_b_coll_elem(p, '=');
859 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
860 == static char p_b_symbol(struct parse *p);
862 static wint_t /* value of symbol */
863 p_b_symbol(struct parse *p)
867 (void)REQUIRE(MORE(), REG_EBRACK);
868 if (!EATTWO('[', '.'))
871 /* collating symbol */
872 value = p_b_coll_elem(p, '.');
873 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
878 - p_b_coll_elem - parse a collating-element name and look it up
879 == static char p_b_coll_elem(struct parse *p, int endc);
881 static wint_t /* value of collating element */
882 p_b_coll_elem(struct parse *p,
883 wint_t endc) /* name ended by endc,']' */
892 while (MORE() && !SEETWO(endc, ']'))
895 SETERROR(REG_EBRACK);
899 for (cp = cnames; cp->name != NULL; cp++)
900 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
901 return(cp->code); /* known name */
902 memset(&mbs, 0, sizeof(mbs));
903 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
904 return (wc); /* single character */
905 else if (clen == (size_t)-1 || clen == (size_t)-2)
906 SETERROR(REG_ILLSEQ);
908 SETERROR(REG_ECOLLATE); /* neither */
913 - othercase - return the case counterpart of an alphabetic
914 == static char othercase(int ch);
916 static wint_t /* if no counterpart, return ch */
919 assert(iswalpha(ch));
921 return(towlower(ch));
922 else if (iswlower(ch))
923 return(towupper(ch));
924 else /* peculiar, but could happen */
929 - bothcases - emit a dualcase version of a two-case character
930 == static void bothcases(struct parse *p, int ch);
932 * Boy, is this implementation ever a kludge...
935 bothcases(struct parse *p, wint_t ch)
937 char *oldnext = p->next;
938 char *oldend = p->end;
939 char bracket[3 + MB_LEN_MAX];
943 assert(othercase(ch) != ch); /* p_bracket() would recurse */
945 memset(&mbs, 0, sizeof(mbs));
946 n = wcrtomb(bracket, ch, &mbs);
947 assert(n != (size_t)-1);
949 bracket[n + 1] = '\0';
950 p->end = bracket+n+1;
952 assert(p->next == p->end);
958 - ordinary - emit an ordinary character
959 == static void ordinary(struct parse *p, int ch);
962 ordinary(struct parse *p, wint_t ch)
966 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
968 else if ((ch & OPDMASK) == ch)
972 * Kludge: character is too big to fit into an OCHAR operand.
973 * Emit a singleton set.
975 if ((cs = allocset(p)) == NULL)
978 EMIT(OANYOF, (int)(cs - p->g->sets));
983 - nonnewline - emit REG_NEWLINE version of OANY
984 == static void nonnewline(struct parse *p);
986 * Boy, is this implementation ever a kludge...
989 nonnewline(struct parse *p)
991 char *oldnext = p->next;
992 char *oldend = p->end;
1002 assert(p->next == bracket+3);
1008 - repeat - generate code for a bounded repetition, recursively if needed
1009 == static void repeat(struct parse *p, sopno start, int from, int to);
1012 repeat(struct parse *p,
1013 sopno start, /* operand from here to end of strip */
1014 int from, /* repeated from this number */
1015 int to) /* to this number of times (maybe INFINITY) */
1017 sopno finish = HERE();
1020 # define REP(f, t) ((f)*8 + (t))
1021 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1024 if (p->error != 0) /* head off possible runaway recursion */
1029 switch (REP(MAP(from), MAP(to))) {
1030 case REP(0, 0): /* must be user doing this */
1031 DROP(finish-start); /* drop the operand */
1033 case REP(0, 1): /* as x{1,1}? */
1034 case REP(0, N): /* as x{1,n}? */
1035 case REP(0, INF): /* as x{1,}? */
1036 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1037 INSERT(OCH_, start); /* offset is wrong... */
1038 repeat(p, start+1, 1, to);
1039 ASTERN(OOR1, start);
1040 AHEAD(start); /* ... fix it */
1043 ASTERN(O_CH, THERETHERE());
1045 case REP(1, 1): /* trivial case */
1048 case REP(1, N): /* as x?x{1,n-1} */
1049 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1050 INSERT(OCH_, start);
1051 ASTERN(OOR1, start);
1053 EMIT(OOR2, 0); /* offset very wrong... */
1054 AHEAD(THERE()); /* ...so fix it */
1055 ASTERN(O_CH, THERETHERE());
1056 copy = dupl(p, start+1, finish+1);
1057 assert(copy == finish+4);
1058 repeat(p, copy, 1, to-1);
1060 case REP(1, INF): /* as x+ */
1061 INSERT(OPLUS_, start);
1062 ASTERN(O_PLUS, start);
1064 case REP(N, N): /* as xx{m-1,n-1} */
1065 copy = dupl(p, start, finish);
1066 repeat(p, copy, from-1, to-1);
1068 case REP(N, INF): /* as xx{n-1,INF} */
1069 copy = dupl(p, start, finish);
1070 repeat(p, copy, from-1, to);
1072 default: /* "can't happen" */
1073 SETERROR(REG_ASSERT); /* just in case */
1079 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1080 - character from the parse struct, signals a REG_ILLSEQ error if the
1081 - character can't be converted. Returns the number of bytes consumed.
1084 wgetnext(struct parse *p)
1090 memset(&mbs, 0, sizeof(mbs));
1091 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1092 if (n == (size_t)-1 || n == (size_t)-2) {
1093 SETERROR(REG_ILLSEQ);
1103 - seterr - set an error condition
1104 == static int seterr(struct parse *p, int e);
1106 static int /* useless but makes type checking happy */
1107 seterr(struct parse *p, int e)
1109 if (p->error == 0) /* keep earliest error condition */
1111 p->next = nuls; /* try to bring things to a halt */
1113 return(0); /* make the return value well-defined */
1117 - allocset - allocate a set of characters for []
1118 == static cset *allocset(struct parse *p);
1121 allocset(struct parse *p)
1125 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1127 SETERROR(REG_ESPACE);
1131 cs = &p->g->sets[p->g->ncsets++];
1132 memset(cs, 0, sizeof(*cs));
1138 - freeset - free a now-unused set
1139 == static void freeset(struct parse *p, cset *cs);
1142 freeset(struct parse *p, cset *cs)
1144 cset *top = &p->g->sets[p->g->ncsets];
1149 memset(cs, 0, sizeof(*cs));
1150 if (cs == top-1) /* recover only the easy case */
1155 - singleton - Determine whether a set contains only one character,
1156 - returning it if so, otherwise returning OUT.
1163 for (i = n = 0; i < NC; i++)
1170 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1172 return (cs->wides[0]);
1173 /* Don't bother handling the other cases. */
1178 - CHadd - add character to character set.
1181 CHadd(struct parse *p, cset *cs, wint_t ch)
1183 wint_t nch, *newwides;
1186 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1188 newwides = realloc(cs->wides, (cs->nwides + 1) *
1189 sizeof(*cs->wides));
1190 if (newwides == NULL) {
1191 SETERROR(REG_ESPACE);
1194 cs->wides = newwides;
1195 cs->wides[cs->nwides++] = ch;
1198 if ((nch = towlower(ch)) < NC)
1199 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1200 if ((nch = towupper(ch)) < NC)
1201 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1206 - CHaddrange - add all characters in the range [min,max] to a character set.
1209 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1213 for (; min < NC && min <= max; min++)
1217 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1218 sizeof(*cs->ranges));
1219 if (newranges == NULL) {
1220 SETERROR(REG_ESPACE);
1223 cs->ranges = newranges;
1224 cs->ranges[cs->nranges].min = min;
1225 cs->ranges[cs->nranges].max = max;
1230 - CHaddtype - add all characters of a certain type to a character set.
1233 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1238 for (i = 0; i < NC; i++)
1239 if (iswctype(i, wct))
1241 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1242 sizeof(*cs->types));
1243 if (newtypes == NULL) {
1244 SETERROR(REG_ESPACE);
1247 cs->types = newtypes;
1248 cs->types[cs->ntypes++] = wct;
1252 - dupl - emit a duplicate of a bunch of sops
1253 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1255 static sopno /* start of duplicate */
1256 dupl(struct parse *p,
1257 sopno start, /* from here */
1258 sopno finish) /* to this less one */
1261 sopno len = finish - start;
1263 assert(finish >= start);
1266 enlarge(p, p->ssize + len); /* this many unexpected additions */
1267 assert(p->ssize >= p->slen + len);
1268 (void) memcpy((char *)(p->strip + p->slen),
1269 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1275 - doemit - emit a strip operator
1276 == static void doemit(struct parse *p, sop op, size_t opnd);
1278 * It might seem better to implement this as a macro with a function as
1279 * hard-case backup, but it's just too big and messy unless there are
1280 * some changes to the data structures. Maybe later.
1283 doemit(struct parse *p, sop op, size_t opnd)
1285 /* avoid making error situations worse */
1289 /* deal with oversize operands ("can't happen", more or less) */
1290 assert(opnd < 1<<OPSHIFT);
1292 /* deal with undersized strip */
1293 if (p->slen >= p->ssize)
1294 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1295 assert(p->slen < p->ssize);
1297 /* finally, it's all reduced to the easy case */
1298 p->strip[p->slen++] = SOP(op, opnd);
1302 - doinsert - insert a sop into the strip
1303 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1306 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1312 /* avoid making error situations worse */
1317 EMIT(op, opnd); /* do checks, ensure space */
1318 assert(HERE() == sn+1);
1321 /* adjust paren pointers */
1323 for (i = 1; i < NPAREN; i++) {
1324 if (p->pbegin[i] >= pos) {
1327 if (p->pend[i] >= pos) {
1332 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1333 (HERE()-pos-1)*sizeof(sop));
1338 - dofwd - complete a forward reference
1339 == static void dofwd(struct parse *p, sopno pos, sop value);
1342 dofwd(struct parse *p, sopno pos, sop value)
1344 /* avoid making error situations worse */
1348 assert(value < 1<<OPSHIFT);
1349 p->strip[pos] = OP(p->strip[pos]) | value;
1353 - enlarge - enlarge the strip
1354 == static void enlarge(struct parse *p, sopno size);
1357 enlarge(struct parse *p, sopno size)
1361 if (p->ssize >= size)
1364 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1366 SETERROR(REG_ESPACE);
1374 - stripsnug - compact the strip
1375 == static void stripsnug(struct parse *p, struct re_guts *g);
1378 stripsnug(struct parse *p, struct re_guts *g)
1380 g->nstates = p->slen;
1381 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1382 if (g->strip == NULL) {
1383 SETERROR(REG_ESPACE);
1384 g->strip = p->strip;
1389 - findmust - fill in must and mlen with longest mandatory literal string
1390 == static void findmust(struct parse *p, struct re_guts *g);
1392 * This algorithm could do fancy things like analyzing the operands of |
1393 * for common subsequences. Someday. This code is simple and finds most
1394 * of the interesting cases.
1396 * Note that must and mlen got initialized during setup.
1399 findmust(struct parse *p, struct re_guts *g)
1408 char buf[MB_LEN_MAX];
1412 /* avoid making error situations worse */
1417 * It's not generally safe to do a ``char'' substring search on
1418 * multibyte character strings, but it's safe for at least
1419 * UTF-8 (see RFC 3629).
1421 if (MB_CUR_MAX > 1 &&
1422 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1425 /* find the longest OCHAR sequence in strip */
1429 scan = g->strip + 1;
1433 case OCHAR: /* sequence member */
1434 if (newlen == 0) { /* new sequence */
1435 memset(&mbs, 0, sizeof(mbs));
1436 newstart = scan - 1;
1438 clen = wcrtomb(buf, OPND(s), &mbs);
1439 if (clen == (size_t)-1)
1443 case OPLUS_: /* things that don't break one */
1447 case OQUEST_: /* things that must be skipped */
1449 offset = altoffset(scan, offset);
1454 /* assert() interferes w debug printouts */
1455 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1460 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1462 case OBOW: /* things that break a sequence */
1469 if (newlen > g->mlen) { /* ends one */
1473 g->moffset += offset;
1476 g->moffset = offset;
1484 if (newlen > g->mlen) { /* ends one */
1488 g->moffset += offset;
1491 g->moffset = offset;
1500 case OANYOF: /* may or may not invalidate offset */
1501 /* First, everything as OANY */
1502 if (newlen > g->mlen) { /* ends one */
1506 g->moffset += offset;
1509 g->moffset = offset;
1520 /* Anything here makes it impossible or too hard
1521 * to calculate the offset -- so we give up;
1522 * save the last known good offset, in case the
1523 * must sequence doesn't occur later.
1525 if (newlen > g->mlen) { /* ends one */
1529 g->moffset += offset;
1531 g->moffset = offset;
1537 } while (OP(s) != OEND);
1539 if (g->mlen == 0) { /* there isn't one */
1544 /* turn it into a character string */
1545 g->must = malloc((size_t)g->mlen + 1);
1546 if (g->must == NULL) { /* argh; just forget it */
1553 memset(&mbs, 0, sizeof(mbs));
1554 while (cp < g->must + g->mlen) {
1555 while (OP(s = *scan++) != OCHAR)
1557 clen = wcrtomb(cp, OPND(s), &mbs);
1558 assert(clen != (size_t)-1);
1561 assert(cp == g->must + g->mlen);
1562 *cp++ = '\0'; /* just on general principles */
1566 - altoffset - choose biggest offset among multiple choices
1567 == static int altoffset(sop *scan, int offset);
1569 * Compute, recursively if necessary, the largest offset among multiple
1573 altoffset(sop *scan, int offset)
1579 /* If we gave up already on offsets, return */
1586 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1595 try = altoffset(scan, try);
1602 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1605 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1606 /* We must skip to the next position, or we'll
1607 * leave altoffset() too early.
1633 return largest+offset;
1637 - computejumps - compute char jumps for BM scan
1638 == static void computejumps(struct parse *p, struct re_guts *g);
1640 * This algorithm assumes g->must exists and is has size greater than
1641 * zero. It's based on the algorithm found on Computer Algorithms by
1644 * A char jump is the number of characters one needs to jump based on
1645 * the value of the character from the text that was mismatched.
1648 computejumps(struct parse *p, struct re_guts *g)
1653 /* Avoid making errors worse */
1657 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1658 if (g->charjump == NULL) /* Not a fatal error */
1660 /* Adjust for signed chars, if necessary */
1661 g->charjump = &g->charjump[-(CHAR_MIN)];
1663 /* If the character does not exist in the pattern, the jump
1664 * is equal to the number of characters in the pattern.
1666 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1667 g->charjump[ch] = g->mlen;
1669 /* If the character does exist, compute the jump that would
1670 * take us to the last character in the pattern equal to it
1671 * (notice that we match right to left, so that last character
1672 * is the first one that would be matched).
1674 for (mindex = 0; mindex < g->mlen; mindex++)
1675 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1679 - computematchjumps - compute match jumps for BM scan
1680 == static void computematchjumps(struct parse *p, struct re_guts *g);
1682 * This algorithm assumes g->must exists and is has size greater than
1683 * zero. It's based on the algorithm found on Computer Algorithms by
1686 * A match jump is the number of characters one needs to advance based
1687 * on the already-matched suffix.
1688 * Notice that all values here are minus (g->mlen-1), because of the way
1689 * the search algorithm works.
1692 computematchjumps(struct parse *p, struct re_guts *g)
1694 int mindex; /* General "must" iterator */
1695 int suffix; /* Keeps track of matching suffix */
1696 int ssuffix; /* Keeps track of suffixes' suffix */
1697 int* pmatches; /* pmatches[k] points to the next i
1698 * such that i+1...mlen is a substring
1699 * of k+1...k+mlen-i-1
1702 /* Avoid making errors worse */
1706 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1707 if (pmatches == NULL) {
1708 g->matchjump = NULL;
1712 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1713 if (g->matchjump == NULL) { /* Not a fatal error */
1718 /* Set maximum possible jump for each character in the pattern */
1719 for (mindex = 0; mindex < g->mlen; mindex++)
1720 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1722 /* Compute pmatches[] */
1723 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1724 mindex--, suffix--) {
1725 pmatches[mindex] = suffix;
1727 /* If a mismatch is found, interrupting the substring,
1728 * compute the matchjump for that position. If no
1729 * mismatch is found, then a text substring mismatched
1730 * against the suffix will also mismatch against the
1733 while (suffix < g->mlen
1734 && g->must[mindex] != g->must[suffix]) {
1735 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1736 g->mlen - mindex - 1);
1737 suffix = pmatches[suffix];
1741 /* Compute the matchjump up to the last substring found to jump
1742 * to the beginning of the largest must pattern prefix matching
1745 for (mindex = 0; mindex <= suffix; mindex++)
1746 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1747 g->mlen + suffix - mindex);
1749 ssuffix = pmatches[suffix];
1750 while (suffix < g->mlen) {
1751 while (suffix <= ssuffix && suffix < g->mlen) {
1752 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1753 g->mlen + ssuffix - suffix);
1756 if (suffix < g->mlen)
1757 ssuffix = pmatches[ssuffix];
1764 - pluscount - count + nesting
1765 == static sopno pluscount(struct parse *p, struct re_guts *g);
1767 static sopno /* nesting depth */
1768 pluscount(struct parse *p, struct re_guts *g)
1776 return(0); /* there may not be an OEND */
1778 scan = g->strip + 1;
1786 if (plusnest > maxnest)
1791 } while (OP(s) != OEND);