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 * Copyright (c) 2011 The FreeBSD Foundation
8 * Portions of this software were developed by David Chisnall
9 * under sponsorship from the FreeBSD Foundation.
11 * This code is derived from software contributed to Berkeley by
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
41 #if defined(LIBC_SCCS) && !defined(lint)
42 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
43 #endif /* LIBC_SCCS and not lint */
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
47 #include <sys/types.h>
65 * parse structure, passed up and down to avoid global variables and
69 char *next; /* next character in RE */
70 char *end; /* end of string (-> NUL normally) */
71 int error; /* has an error been seen? */
72 sop *strip; /* malloced strip */
73 sopno ssize; /* malloced strip size (allocated) */
74 sopno slen; /* malloced strip length (used) */
75 int ncsalloc; /* number of csets allocated */
77 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
78 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
79 sopno pend[NPAREN]; /* -> ) ([0] unused) */
82 /* ========= begin header generated by ./mkh ========= */
87 /* === regcomp.c === */
88 static void p_ere(struct parse *p, int stop);
89 static void p_ere_exp(struct parse *p);
90 static void p_str(struct parse *p);
91 static void p_bre(struct parse *p, int end1, int end2);
92 static int p_simp_re(struct parse *p, int starordinary);
93 static int p_count(struct parse *p);
94 static void p_bracket(struct parse *p);
95 static void p_b_term(struct parse *p, cset *cs);
96 static void p_b_cclass(struct parse *p, cset *cs);
97 static void p_b_eclass(struct parse *p, cset *cs);
98 static wint_t p_b_symbol(struct parse *p);
99 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
100 static wint_t othercase(wint_t ch);
101 static void bothcases(struct parse *p, wint_t ch);
102 static void ordinary(struct parse *p, wint_t ch);
103 static void nonnewline(struct parse *p);
104 static void repeat(struct parse *p, sopno start, int from, int to);
105 static int seterr(struct parse *p, int e);
106 static cset *allocset(struct parse *p);
107 static void freeset(struct parse *p, cset *cs);
108 static void CHadd(struct parse *p, cset *cs, wint_t ch);
109 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
110 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
111 static wint_t singleton(cset *cs);
112 static sopno dupl(struct parse *p, sopno start, sopno finish);
113 static void doemit(struct parse *p, sop op, size_t opnd);
114 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
115 static void dofwd(struct parse *p, sopno pos, sop value);
116 static int enlarge(struct parse *p, sopno size);
117 static void stripsnug(struct parse *p, struct re_guts *g);
118 static void findmust(struct parse *p, struct re_guts *g);
119 static int altoffset(sop *scan, int offset);
120 static void computejumps(struct parse *p, struct re_guts *g);
121 static void computematchjumps(struct parse *p, struct re_guts *g);
122 static sopno pluscount(struct parse *p, struct re_guts *g);
123 static wint_t wgetnext(struct parse *p);
128 /* ========= end header generated by ./mkh ========= */
130 static char nuls[10]; /* place to point scanner in event of error */
133 * macros for use with parse structure
134 * BEWARE: these know that the parse structure is named `p' !!!
136 #define PEEK() (*p->next)
137 #define PEEK2() (*(p->next+1))
138 #define MORE() (p->next < p->end)
139 #define MORE2() (p->next+1 < p->end)
140 #define SEE(c) (MORE() && PEEK() == (c))
141 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
142 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
143 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
144 #define NEXT() (p->next++)
145 #define NEXT2() (p->next += 2)
146 #define NEXTn(n) (p->next += (n))
147 #define GETNEXT() (*p->next++)
148 #define WGETNEXT() wgetnext(p)
149 #define SETERROR(e) seterr(p, (e))
150 #define REQUIRE(co, e) ((co) || SETERROR(e))
151 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
152 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
153 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
154 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
155 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
156 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
157 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
158 #define HERE() (p->slen)
159 #define THERE() (p->slen - 1)
160 #define THERETHERE() (p->slen - 2)
161 #define DROP(n) (p->slen -= (n))
164 static int never = 0; /* for use in asserts; shuts lint up */
166 #define never 0 /* some <assert.h>s have bugs too */
169 /* Macro used by computejump()/computematchjump() */
170 #define MIN(a,b) ((a)<(b)?(a):(b))
173 - regcomp - interface for parser and compilation
174 = extern int regcomp(regex_t *, const char *, int);
175 = #define REG_BASIC 0000
176 = #define REG_EXTENDED 0001
177 = #define REG_ICASE 0002
178 = #define REG_NOSUB 0004
179 = #define REG_NEWLINE 0010
180 = #define REG_NOSPEC 0020
181 = #define REG_PEND 0040
182 = #define REG_DUMP 0200
184 int /* 0 success, otherwise REG_something */
185 regcomp(regex_t * __restrict preg,
186 const char * __restrict pattern,
191 struct parse *p = &pa;
196 # define GOODFLAGS(f) (f)
198 # define GOODFLAGS(f) ((f)&~REG_DUMP)
201 cflags = GOODFLAGS(cflags);
202 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
205 if (cflags®_PEND) {
206 if (preg->re_endp < pattern)
208 len = preg->re_endp - pattern;
210 len = strlen((char *)pattern);
212 /* do the mallocs early so failure handling is easy */
213 g = (struct re_guts *)malloc(sizeof(struct re_guts));
217 * Limit the pattern space to avoid a 32-bit overflow on buffer
218 * extension. Also avoid any signed overflow in case of conversion
219 * so make the real limit based on a 31-bit overflow.
221 * Likely not applicable on 64-bit systems but handle the case
222 * generically (who are we to stop people from using ~715MB+
225 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
230 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
231 assert(p->ssize >= len);
233 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
235 if (p->strip == NULL) {
242 p->next = (char *)pattern; /* convenience; we do not modify it */
243 p->end = p->next + len;
246 for (i = 0; i < NPAREN; i++) {
266 g->firststate = THERE();
267 if (cflags®_EXTENDED)
269 else if (cflags®_NOSPEC)
274 g->laststate = THERE();
276 /* tidy up loose ends and fill things in */
279 /* only use Boyer-Moore algorithm if the pattern is bigger
280 * than three characters
284 computematchjumps(p, g);
285 if(g->matchjump == NULL && g->charjump != NULL) {
290 g->nplus = pluscount(p, g);
292 preg->re_nsub = g->nsub;
294 preg->re_magic = MAGIC1;
296 /* not debugging, so can't rely on the assert() in regexec() */
298 SETERROR(REG_ASSERT);
301 /* win or lose, we're done */
302 if (p->error != 0) /* lose */
308 - p_ere - ERE parser top level, concatenation and alternation
309 == static void p_ere(struct parse *p, int_t stop);
312 p_ere(struct parse *p,
313 int stop) /* character this ERE should end at */
319 int first = 1; /* is this the first alternative? */
322 /* do a bunch of concatenated expressions */
324 while (MORE() && (c = PEEK()) != '|' && c != stop)
326 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
329 break; /* NOTE BREAK OUT */
332 INSERT(OCH_, conc); /* offset is wrong */
337 ASTERN(OOR1, prevback);
339 AHEAD(prevfwd); /* fix previous offset */
341 EMIT(OOR2, 0); /* offset is very wrong */
344 if (!first) { /* tail-end fixups */
346 ASTERN(O_CH, prevback);
349 assert(!MORE() || SEE(stop));
353 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
354 == static void p_ere_exp(struct parse *p);
357 p_ere_exp(struct parse *p)
367 assert(MORE()); /* caller should have ensured this */
373 (void)REQUIRE(MORE(), REG_EPAREN);
377 p->pbegin[subno] = HERE();
378 EMIT(OLPAREN, subno);
381 if (subno < NPAREN) {
382 p->pend[subno] = HERE();
383 assert(p->pend[subno] != 0);
385 EMIT(ORPAREN, subno);
386 (void)MUSTEAT(')', REG_EPAREN);
388 #ifndef POSIX_MISTAKE
389 case ')': /* happens only if no current unmatched ( */
391 * You may ask, why the ifndef? Because I didn't notice
392 * this until slightly too late for 1003.2, and none of the
393 * other 1003.2 regular-expression reviewers noticed it at
394 * all. So an unmatched ) is legal POSIX, at least until
395 * we can get it fixed.
397 SETERROR(REG_EPAREN);
402 p->g->iflags |= USEBOL;
408 p->g->iflags |= USEEOL;
417 SETERROR(REG_BADRPT);
420 if (p->g->cflags®_NEWLINE)
429 (void)REQUIRE(MORE(), REG_EESCAPE);
443 case '{': /* okay as ordinary except if digit follows */
444 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
456 /* we call { a repetition if followed by a digit */
457 if (!( c == '*' || c == '+' || c == '?' ||
458 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
459 return; /* no repetition, we're done */
462 (void)REQUIRE(!wascaret, REG_BADRPT);
464 case '*': /* implemented as +? */
465 /* this case does not require the (y|) trick, noKLUDGE */
468 INSERT(OQUEST_, pos);
469 ASTERN(O_QUEST, pos);
476 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
477 INSERT(OCH_, pos); /* offset slightly wrong */
478 ASTERN(OOR1, pos); /* this one's right */
479 AHEAD(pos); /* fix the OCH_ */
480 EMIT(OOR2, 0); /* offset very wrong... */
481 AHEAD(THERE()); /* ...so fix it */
482 ASTERN(O_CH, THERETHERE());
487 if (isdigit((uch)PEEK())) {
489 (void)REQUIRE(count <= count2, REG_BADBR);
490 } else /* single number with comma */
492 } else /* just a single number */
494 repeat(p, pos, count, count2);
495 if (!EAT('}')) { /* error heuristics */
496 while (MORE() && PEEK() != '}')
498 (void)REQUIRE(MORE(), REG_EBRACE);
507 if (!( c == '*' || c == '+' || c == '?' ||
508 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
510 SETERROR(REG_BADRPT);
514 - p_str - string (no metacharacters) "parser"
515 == static void p_str(struct parse *p);
518 p_str(struct parse *p)
520 (void)REQUIRE(MORE(), REG_EMPTY);
522 ordinary(p, WGETNEXT());
526 - p_bre - BRE parser top level, anchoring and concatenation
527 == static void p_bre(struct parse *p, int end1, \
529 * Giving end1 as OUT essentially eliminates the end1/end2 check.
531 * This implementation is a bit of a kludge, in that a trailing $ is first
532 * taken as an ordinary character and then revised to be an anchor.
533 * The amount of lookahead needed to avoid this kludge is excessive.
536 p_bre(struct parse *p,
537 int end1, /* first terminating character */
538 int end2) /* second terminating character */
540 sopno start = HERE();
541 int first = 1; /* first subexpression? */
546 p->g->iflags |= USEBOL;
549 while (MORE() && !SEETWO(end1, end2)) {
550 wasdollar = p_simp_re(p, first);
553 if (wasdollar) { /* oops, that was a trailing anchor */
556 p->g->iflags |= USEEOL;
560 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
564 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
565 == static int p_simp_re(struct parse *p, int starordinary);
567 static int /* was the simple RE an unbackslashed $? */
568 p_simp_re(struct parse *p,
569 int starordinary) /* is a leading * an ordinary character? */
578 # define BACKSL (1<<CHAR_BIT)
580 pos = HERE(); /* repetition op, if any, covers from here */
582 assert(MORE()); /* caller should have ensured this */
585 (void)REQUIRE(MORE(), REG_EESCAPE);
586 c = BACKSL | GETNEXT();
590 if (p->g->cflags®_NEWLINE)
605 SETERROR(REG_BADRPT);
611 p->pbegin[subno] = HERE();
612 EMIT(OLPAREN, subno);
613 /* the MORE here is an error heuristic */
614 if (MORE() && !SEETWO('\\', ')'))
616 if (subno < NPAREN) {
617 p->pend[subno] = HERE();
618 assert(p->pend[subno] != 0);
620 EMIT(ORPAREN, subno);
621 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
623 case BACKSL|')': /* should not get here -- must be user */
625 SETERROR(REG_EPAREN);
636 i = (c&~BACKSL) - '0';
638 if (p->pend[i] != 0) {
639 assert(i <= p->g->nsub);
641 assert(p->pbegin[i] != 0);
642 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
643 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
644 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
647 SETERROR(REG_ESUBREG);
651 (void)REQUIRE(starordinary, REG_BADRPT);
660 if (EAT('*')) { /* implemented as +? */
661 /* this case does not require the (y|) trick, noKLUDGE */
664 INSERT(OQUEST_, pos);
665 ASTERN(O_QUEST, pos);
666 } else if (EATTWO('\\', '{')) {
669 if (MORE() && isdigit((uch)PEEK())) {
671 (void)REQUIRE(count <= count2, REG_BADBR);
672 } else /* single number with comma */
674 } else /* just a single number */
676 repeat(p, pos, count, count2);
677 if (!EATTWO('\\', '}')) { /* error heuristics */
678 while (MORE() && !SEETWO('\\', '}'))
680 (void)REQUIRE(MORE(), REG_EBRACE);
683 } else if (c == '$') /* $ (but not \$) ends it */
690 - p_count - parse a repetition count
691 == static int p_count(struct parse *p);
693 static int /* the value */
694 p_count(struct parse *p)
699 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
700 count = count*10 + (GETNEXT() - '0');
704 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
709 - p_bracket - parse a bracketed character list
710 == static void p_bracket(struct parse *p);
713 p_bracket(struct parse *p)
718 /* Dept of Truly Sickening Special-Case Kludges */
719 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
724 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
730 if ((cs = allocset(p)) == NULL)
733 if (p->g->cflags®_ICASE)
741 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
745 (void)MUSTEAT(']', REG_EBRACK);
747 if (p->error != 0) /* don't mess things up further */
750 if (cs->invert && p->g->cflags®_NEWLINE)
751 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
753 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
757 EMIT(OANYOF, (int)(cs - p->g->sets));
761 - p_b_term - parse one term of a bracketed character list
762 == static void p_b_term(struct parse *p, cset *cs);
765 p_b_term(struct parse *p, cset *cs)
768 wint_t start, finish;
770 struct xlocale_collate *table =
771 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
773 /* classify what we've got */
774 switch ((MORE()) ? PEEK() : '\0') {
776 c = (MORE2()) ? PEEK2() : '\0';
779 SETERROR(REG_ERANGE);
780 return; /* NOTE RETURN */
787 case ':': /* character class */
789 (void)REQUIRE(MORE(), REG_EBRACK);
791 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
793 (void)REQUIRE(MORE(), REG_EBRACK);
794 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
796 case '=': /* equivalence class */
798 (void)REQUIRE(MORE(), REG_EBRACK);
800 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
802 (void)REQUIRE(MORE(), REG_EBRACK);
803 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
805 default: /* symbol, ordinary character, or range */
806 start = p_b_symbol(p);
807 if (SEE('-') && MORE2() && PEEK2() != ']') {
813 finish = p_b_symbol(p);
819 if (table->__collate_load_error || MB_CUR_MAX > 1) {
820 (void)REQUIRE(start <= finish, REG_ERANGE);
821 CHaddrange(p, cs, start, finish);
823 (void)REQUIRE(__wcollate_range_cmp(start, finish) <= 0, REG_ERANGE);
824 for (i = 0; i <= UCHAR_MAX; i++) {
825 if ( __wcollate_range_cmp(start, i) <= 0
826 && __wcollate_range_cmp(i, finish) <= 0
837 - p_b_cclass - parse a character-class name and deal with it
838 == static void p_b_cclass(struct parse *p, cset *cs);
841 p_b_cclass(struct parse *p, cset *cs)
848 while (MORE() && isalpha((uch)PEEK()))
851 if (len >= sizeof(clname) - 1) {
852 SETERROR(REG_ECTYPE);
855 memcpy(clname, sp, len);
857 if ((wct = wctype(clname)) == 0) {
858 SETERROR(REG_ECTYPE);
861 CHaddtype(p, cs, wct);
865 - p_b_eclass - parse an equivalence-class name and deal with it
866 == static void p_b_eclass(struct parse *p, cset *cs);
868 * This implementation is incomplete. xxx
871 p_b_eclass(struct parse *p, cset *cs)
875 c = p_b_coll_elem(p, '=');
880 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
881 == static wint_t p_b_symbol(struct parse *p);
883 static wint_t /* value of symbol */
884 p_b_symbol(struct parse *p)
888 (void)REQUIRE(MORE(), REG_EBRACK);
889 if (!EATTWO('[', '.'))
892 /* collating symbol */
893 value = p_b_coll_elem(p, '.');
894 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
899 - p_b_coll_elem - parse a collating-element name and look it up
900 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
902 static wint_t /* value of collating element */
903 p_b_coll_elem(struct parse *p,
904 wint_t endc) /* name ended by endc,']' */
913 while (MORE() && !SEETWO(endc, ']'))
916 SETERROR(REG_EBRACK);
920 for (cp = cnames; cp->name != NULL; cp++)
921 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
922 return(cp->code); /* known name */
923 memset(&mbs, 0, sizeof(mbs));
924 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
925 return (wc); /* single character */
926 else if (clen == (size_t)-1 || clen == (size_t)-2)
927 SETERROR(REG_ILLSEQ);
929 SETERROR(REG_ECOLLATE); /* neither */
934 - othercase - return the case counterpart of an alphabetic
935 == static wint_t othercase(wint_t ch);
937 static wint_t /* if no counterpart, return ch */
940 assert(iswalpha(ch));
942 return(towlower(ch));
943 else if (iswlower(ch))
944 return(towupper(ch));
945 else /* peculiar, but could happen */
950 - bothcases - emit a dualcase version of a two-case character
951 == static void bothcases(struct parse *p, wint_t ch);
953 * Boy, is this implementation ever a kludge...
956 bothcases(struct parse *p, wint_t ch)
958 char *oldnext = p->next;
959 char *oldend = p->end;
960 char bracket[3 + MB_LEN_MAX];
964 assert(othercase(ch) != ch); /* p_bracket() would recurse */
966 memset(&mbs, 0, sizeof(mbs));
967 n = wcrtomb(bracket, ch, &mbs);
968 assert(n != (size_t)-1);
970 bracket[n + 1] = '\0';
971 p->end = bracket+n+1;
973 assert(p->next == p->end);
979 - ordinary - emit an ordinary character
980 == static void ordinary(struct parse *p, wint_t ch);
983 ordinary(struct parse *p, wint_t ch)
987 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
989 else if ((ch & OPDMASK) == ch)
993 * Kludge: character is too big to fit into an OCHAR operand.
994 * Emit a singleton set.
996 if ((cs = allocset(p)) == NULL)
999 EMIT(OANYOF, (int)(cs - p->g->sets));
1004 - nonnewline - emit REG_NEWLINE version of OANY
1005 == static void nonnewline(struct parse *p);
1007 * Boy, is this implementation ever a kludge...
1010 nonnewline(struct parse *p)
1012 char *oldnext = p->next;
1013 char *oldend = p->end;
1023 assert(p->next == bracket+3);
1029 - repeat - generate code for a bounded repetition, recursively if needed
1030 == static void repeat(struct parse *p, sopno start, int from, int to);
1033 repeat(struct parse *p,
1034 sopno start, /* operand from here to end of strip */
1035 int from, /* repeated from this number */
1036 int to) /* to this number of times (maybe INFINITY) */
1038 sopno finish = HERE();
1041 # define REP(f, t) ((f)*8 + (t))
1042 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1045 if (p->error != 0) /* head off possible runaway recursion */
1050 switch (REP(MAP(from), MAP(to))) {
1051 case REP(0, 0): /* must be user doing this */
1052 DROP(finish-start); /* drop the operand */
1054 case REP(0, 1): /* as x{1,1}? */
1055 case REP(0, N): /* as x{1,n}? */
1056 case REP(0, INF): /* as x{1,}? */
1057 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1058 INSERT(OCH_, start); /* offset is wrong... */
1059 repeat(p, start+1, 1, to);
1060 ASTERN(OOR1, start);
1061 AHEAD(start); /* ... fix it */
1064 ASTERN(O_CH, THERETHERE());
1066 case REP(1, 1): /* trivial case */
1069 case REP(1, N): /* as x?x{1,n-1} */
1070 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1071 INSERT(OCH_, start);
1072 ASTERN(OOR1, start);
1074 EMIT(OOR2, 0); /* offset very wrong... */
1075 AHEAD(THERE()); /* ...so fix it */
1076 ASTERN(O_CH, THERETHERE());
1077 copy = dupl(p, start+1, finish+1);
1078 assert(copy == finish+4);
1079 repeat(p, copy, 1, to-1);
1081 case REP(1, INF): /* as x+ */
1082 INSERT(OPLUS_, start);
1083 ASTERN(O_PLUS, start);
1085 case REP(N, N): /* as xx{m-1,n-1} */
1086 copy = dupl(p, start, finish);
1087 repeat(p, copy, from-1, to-1);
1089 case REP(N, INF): /* as xx{n-1,INF} */
1090 copy = dupl(p, start, finish);
1091 repeat(p, copy, from-1, to);
1093 default: /* "can't happen" */
1094 SETERROR(REG_ASSERT); /* just in case */
1100 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1101 - character from the parse struct, signals a REG_ILLSEQ error if the
1102 - character can't be converted. Returns the number of bytes consumed.
1105 wgetnext(struct parse *p)
1111 memset(&mbs, 0, sizeof(mbs));
1112 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1113 if (n == (size_t)-1 || n == (size_t)-2) {
1114 SETERROR(REG_ILLSEQ);
1124 - seterr - set an error condition
1125 == static int seterr(struct parse *p, int e);
1127 static int /* useless but makes type checking happy */
1128 seterr(struct parse *p, int e)
1130 if (p->error == 0) /* keep earliest error condition */
1132 p->next = nuls; /* try to bring things to a halt */
1134 return(0); /* make the return value well-defined */
1138 - allocset - allocate a set of characters for []
1139 == static cset *allocset(struct parse *p);
1142 allocset(struct parse *p)
1146 ncs = reallocarray(p->g->sets, p->g->ncsets + 1, sizeof(*ncs));
1148 SETERROR(REG_ESPACE);
1152 cs = &p->g->sets[p->g->ncsets++];
1153 memset(cs, 0, sizeof(*cs));
1159 - freeset - free a now-unused set
1160 == static void freeset(struct parse *p, cset *cs);
1163 freeset(struct parse *p, cset *cs)
1165 cset *top = &p->g->sets[p->g->ncsets];
1170 memset(cs, 0, sizeof(*cs));
1171 if (cs == top-1) /* recover only the easy case */
1176 - singleton - Determine whether a set contains only one character,
1177 - returning it if so, otherwise returning OUT.
1184 for (i = n = 0; i < NC; i++)
1191 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1193 return (cs->wides[0]);
1194 /* Don't bother handling the other cases. */
1199 - CHadd - add character to character set.
1202 CHadd(struct parse *p, cset *cs, wint_t ch)
1204 wint_t nch, *newwides;
1207 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1209 newwides = reallocarray(cs->wides, cs->nwides + 1,
1210 sizeof(*cs->wides));
1211 if (newwides == NULL) {
1212 SETERROR(REG_ESPACE);
1215 cs->wides = newwides;
1216 cs->wides[cs->nwides++] = ch;
1219 if ((nch = towlower(ch)) < NC)
1220 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1221 if ((nch = towupper(ch)) < NC)
1222 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1227 - CHaddrange - add all characters in the range [min,max] to a character set.
1230 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1234 for (; min < NC && min <= max; min++)
1238 newranges = reallocarray(cs->ranges, cs->nranges + 1,
1239 sizeof(*cs->ranges));
1240 if (newranges == NULL) {
1241 SETERROR(REG_ESPACE);
1244 cs->ranges = newranges;
1245 cs->ranges[cs->nranges].min = min;
1246 cs->ranges[cs->nranges].max = max;
1251 - CHaddtype - add all characters of a certain type to a character set.
1254 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1259 for (i = 0; i < NC; i++)
1260 if (iswctype(i, wct))
1262 newtypes = reallocarray(cs->types, cs->ntypes + 1,
1263 sizeof(*cs->types));
1264 if (newtypes == NULL) {
1265 SETERROR(REG_ESPACE);
1268 cs->types = newtypes;
1269 cs->types[cs->ntypes++] = wct;
1273 - dupl - emit a duplicate of a bunch of sops
1274 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1276 static sopno /* start of duplicate */
1277 dupl(struct parse *p,
1278 sopno start, /* from here */
1279 sopno finish) /* to this less one */
1282 sopno len = finish - start;
1284 assert(finish >= start);
1287 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1289 (void) memcpy((char *)(p->strip + p->slen),
1290 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1296 - doemit - emit a strip operator
1297 == static void doemit(struct parse *p, sop op, size_t opnd);
1299 * It might seem better to implement this as a macro with a function as
1300 * hard-case backup, but it's just too big and messy unless there are
1301 * some changes to the data structures. Maybe later.
1304 doemit(struct parse *p, sop op, size_t opnd)
1306 /* avoid making error situations worse */
1310 /* deal with oversize operands ("can't happen", more or less) */
1311 assert(opnd < 1<<OPSHIFT);
1313 /* deal with undersized strip */
1314 if (p->slen >= p->ssize)
1315 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1318 /* finally, it's all reduced to the easy case */
1319 p->strip[p->slen++] = SOP(op, opnd);
1323 - doinsert - insert a sop into the strip
1324 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1327 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1333 /* avoid making error situations worse */
1338 EMIT(op, opnd); /* do checks, ensure space */
1339 assert(HERE() == sn+1);
1342 /* adjust paren pointers */
1344 for (i = 1; i < NPAREN; i++) {
1345 if (p->pbegin[i] >= pos) {
1348 if (p->pend[i] >= pos) {
1353 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1354 (HERE()-pos-1)*sizeof(sop));
1359 - dofwd - complete a forward reference
1360 == static void dofwd(struct parse *p, sopno pos, sop value);
1363 dofwd(struct parse *p, sopno pos, sop value)
1365 /* avoid making error situations worse */
1369 assert(value < 1<<OPSHIFT);
1370 p->strip[pos] = OP(p->strip[pos]) | value;
1374 - enlarge - enlarge the strip
1375 == static int enlarge(struct parse *p, sopno size);
1378 enlarge(struct parse *p, sopno size)
1382 if (p->ssize >= size)
1385 sp = reallocarray(p->strip, size, sizeof(sop));
1387 SETERROR(REG_ESPACE);
1396 - stripsnug - compact the strip
1397 == static void stripsnug(struct parse *p, struct re_guts *g);
1400 stripsnug(struct parse *p, struct re_guts *g)
1402 g->nstates = p->slen;
1403 g->strip = reallocarray((char *)p->strip, p->slen, sizeof(sop));
1404 if (g->strip == NULL) {
1405 SETERROR(REG_ESPACE);
1406 g->strip = p->strip;
1411 - findmust - fill in must and mlen with longest mandatory literal string
1412 == static void findmust(struct parse *p, struct re_guts *g);
1414 * This algorithm could do fancy things like analyzing the operands of |
1415 * for common subsequences. Someday. This code is simple and finds most
1416 * of the interesting cases.
1418 * Note that must and mlen got initialized during setup.
1421 findmust(struct parse *p, struct re_guts *g)
1425 sop *newstart = NULL;
1430 char buf[MB_LEN_MAX];
1434 /* avoid making error situations worse */
1439 * It's not generally safe to do a ``char'' substring search on
1440 * multibyte character strings, but it's safe for at least
1441 * UTF-8 (see RFC 3629).
1443 if (MB_CUR_MAX > 1 &&
1444 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1447 /* find the longest OCHAR sequence in strip */
1451 scan = g->strip + 1;
1455 case OCHAR: /* sequence member */
1456 if (newlen == 0) { /* new sequence */
1457 memset(&mbs, 0, sizeof(mbs));
1458 newstart = scan - 1;
1460 clen = wcrtomb(buf, OPND(s), &mbs);
1461 if (clen == (size_t)-1)
1465 case OPLUS_: /* things that don't break one */
1469 case OQUEST_: /* things that must be skipped */
1471 offset = altoffset(scan, offset);
1476 /* assert() interferes w debug printouts */
1477 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1482 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1484 case OBOW: /* things that break a sequence */
1491 if (newlen > g->mlen) { /* ends one */
1495 g->moffset += offset;
1498 g->moffset = offset;
1506 if (newlen > g->mlen) { /* ends one */
1510 g->moffset += offset;
1513 g->moffset = offset;
1522 case OANYOF: /* may or may not invalidate offset */
1523 /* First, everything as OANY */
1524 if (newlen > g->mlen) { /* ends one */
1528 g->moffset += offset;
1531 g->moffset = offset;
1542 /* Anything here makes it impossible or too hard
1543 * to calculate the offset -- so we give up;
1544 * save the last known good offset, in case the
1545 * must sequence doesn't occur later.
1547 if (newlen > g->mlen) { /* ends one */
1551 g->moffset += offset;
1553 g->moffset = offset;
1559 } while (OP(s) != OEND);
1561 if (g->mlen == 0) { /* there isn't one */
1566 /* turn it into a character string */
1567 g->must = malloc((size_t)g->mlen + 1);
1568 if (g->must == NULL) { /* argh; just forget it */
1575 memset(&mbs, 0, sizeof(mbs));
1576 while (cp < g->must + g->mlen) {
1577 while (OP(s = *scan++) != OCHAR)
1579 clen = wcrtomb(cp, OPND(s), &mbs);
1580 assert(clen != (size_t)-1);
1583 assert(cp == g->must + g->mlen);
1584 *cp++ = '\0'; /* just on general principles */
1588 - altoffset - choose biggest offset among multiple choices
1589 == static int altoffset(sop *scan, int offset);
1591 * Compute, recursively if necessary, the largest offset among multiple
1595 altoffset(sop *scan, int offset)
1601 /* If we gave up already on offsets, return */
1608 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1617 try = altoffset(scan, try);
1624 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1627 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1628 /* We must skip to the next position, or we'll
1629 * leave altoffset() too early.
1655 return largest+offset;
1659 - computejumps - compute char jumps for BM scan
1660 == static void computejumps(struct parse *p, struct re_guts *g);
1662 * This algorithm assumes g->must exists and is has size greater than
1663 * zero. It's based on the algorithm found on Computer Algorithms by
1666 * A char jump is the number of characters one needs to jump based on
1667 * the value of the character from the text that was mismatched.
1670 computejumps(struct parse *p, struct re_guts *g)
1675 /* Avoid making errors worse */
1679 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1680 if (g->charjump == NULL) /* Not a fatal error */
1682 /* Adjust for signed chars, if necessary */
1683 g->charjump = &g->charjump[-(CHAR_MIN)];
1685 /* If the character does not exist in the pattern, the jump
1686 * is equal to the number of characters in the pattern.
1688 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1689 g->charjump[ch] = g->mlen;
1691 /* If the character does exist, compute the jump that would
1692 * take us to the last character in the pattern equal to it
1693 * (notice that we match right to left, so that last character
1694 * is the first one that would be matched).
1696 for (mindex = 0; mindex < g->mlen; mindex++)
1697 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1701 - computematchjumps - compute match jumps for BM scan
1702 == static void computematchjumps(struct parse *p, struct re_guts *g);
1704 * This algorithm assumes g->must exists and is has size greater than
1705 * zero. It's based on the algorithm found on Computer Algorithms by
1708 * A match jump is the number of characters one needs to advance based
1709 * on the already-matched suffix.
1710 * Notice that all values here are minus (g->mlen-1), because of the way
1711 * the search algorithm works.
1714 computematchjumps(struct parse *p, struct re_guts *g)
1716 int mindex; /* General "must" iterator */
1717 int suffix; /* Keeps track of matching suffix */
1718 int ssuffix; /* Keeps track of suffixes' suffix */
1719 int* pmatches; /* pmatches[k] points to the next i
1720 * such that i+1...mlen is a substring
1721 * of k+1...k+mlen-i-1
1724 /* Avoid making errors worse */
1728 pmatches = (int*) malloc(g->mlen * sizeof(int));
1729 if (pmatches == NULL) {
1730 g->matchjump = NULL;
1734 g->matchjump = (int*) malloc(g->mlen * sizeof(int));
1735 if (g->matchjump == NULL) { /* Not a fatal error */
1740 /* Set maximum possible jump for each character in the pattern */
1741 for (mindex = 0; mindex < g->mlen; mindex++)
1742 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1744 /* Compute pmatches[] */
1745 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1746 mindex--, suffix--) {
1747 pmatches[mindex] = suffix;
1749 /* If a mismatch is found, interrupting the substring,
1750 * compute the matchjump for that position. If no
1751 * mismatch is found, then a text substring mismatched
1752 * against the suffix will also mismatch against the
1755 while (suffix < g->mlen
1756 && g->must[mindex] != g->must[suffix]) {
1757 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1758 g->mlen - mindex - 1);
1759 suffix = pmatches[suffix];
1763 /* Compute the matchjump up to the last substring found to jump
1764 * to the beginning of the largest must pattern prefix matching
1767 for (mindex = 0; mindex <= suffix; mindex++)
1768 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1769 g->mlen + suffix - mindex);
1771 ssuffix = pmatches[suffix];
1772 while (suffix < g->mlen) {
1773 while (suffix <= ssuffix && suffix < g->mlen) {
1774 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1775 g->mlen + ssuffix - suffix);
1778 if (suffix < g->mlen)
1779 ssuffix = pmatches[ssuffix];
1786 - pluscount - count + nesting
1787 == static sopno pluscount(struct parse *p, struct re_guts *g);
1789 static sopno /* nesting depth */
1790 pluscount(struct parse *p, struct re_guts *g)
1798 return(0); /* there may not be an OEND */
1800 scan = g->strip + 1;
1808 if (plusnest > maxnest)
1813 } while (OP(s) != OEND);