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>
66 * parse structure, passed up and down to avoid global variables and
70 char *next; /* next character in RE */
71 char *end; /* end of string (-> NUL normally) */
72 int error; /* has an error been seen? */
73 sop *strip; /* malloced strip */
74 sopno ssize; /* malloced strip size (allocated) */
75 sopno slen; /* malloced strip length (used) */
76 int ncsalloc; /* number of csets allocated */
78 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
79 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
80 sopno pend[NPAREN]; /* -> ) ([0] unused) */
83 /* ========= begin header generated by ./mkh ========= */
88 /* === regcomp.c === */
89 static void p_ere(struct parse *p, wint_t stop);
90 static void p_ere_exp(struct parse *p);
91 static void p_str(struct parse *p);
92 static void p_bre(struct parse *p, wint_t end1, wint_t end2);
93 static int p_simp_re(struct parse *p, int starordinary);
94 static int p_count(struct parse *p);
95 static void p_bracket(struct parse *p);
96 static void p_b_term(struct parse *p, cset *cs);
97 static void p_b_cclass(struct parse *p, cset *cs);
98 static void p_b_eclass(struct parse *p, cset *cs);
99 static wint_t p_b_symbol(struct parse *p);
100 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
101 static wint_t othercase(wint_t ch);
102 static void bothcases(struct parse *p, wint_t ch);
103 static void ordinary(struct parse *p, wint_t ch);
104 static void nonnewline(struct parse *p);
105 static void repeat(struct parse *p, sopno start, int from, int to);
106 static int seterr(struct parse *p, int e);
107 static cset *allocset(struct parse *p);
108 static void freeset(struct parse *p, cset *cs);
109 static void CHadd(struct parse *p, cset *cs, wint_t ch);
110 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
111 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
112 static wint_t singleton(cset *cs);
113 static sopno dupl(struct parse *p, sopno start, sopno finish);
114 static void doemit(struct parse *p, sop op, size_t opnd);
115 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
116 static void dofwd(struct parse *p, sopno pos, sop value);
117 static void enlarge(struct parse *p, sopno size);
118 static void stripsnug(struct parse *p, struct re_guts *g);
119 static void findmust(struct parse *p, struct re_guts *g);
120 static int altoffset(sop *scan, int offset);
121 static void computejumps(struct parse *p, struct re_guts *g);
122 static void computematchjumps(struct parse *p, struct re_guts *g);
123 static sopno pluscount(struct parse *p, struct re_guts *g);
124 static wint_t wgetnext(struct parse *p);
129 /* ========= end header generated by ./mkh ========= */
131 static char nuls[10]; /* place to point scanner in event of error */
134 * macros for use with parse structure
135 * BEWARE: these know that the parse structure is named `p' !!!
137 #define PEEK() (*p->next)
138 #define PEEK2() (*(p->next+1))
139 #define MORE() (p->next < p->end)
140 #define MORE2() (p->next+1 < p->end)
141 #define SEE(c) (MORE() && PEEK() == (c))
142 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
143 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
144 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
145 #define NEXT() (p->next++)
146 #define NEXT2() (p->next += 2)
147 #define NEXTn(n) (p->next += (n))
148 #define GETNEXT() (*p->next++)
149 #define WGETNEXT() wgetnext(p)
150 #define SETERROR(e) seterr(p, (e))
151 #define REQUIRE(co, e) ((co) || SETERROR(e))
152 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
153 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
154 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
155 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
156 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
157 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
158 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
159 #define HERE() (p->slen)
160 #define THERE() (p->slen - 1)
161 #define THERETHERE() (p->slen - 2)
162 #define DROP(n) (p->slen -= (n))
165 static int never = 0; /* for use in asserts; shuts lint up */
167 #define never 0 /* some <assert.h>s have bugs too */
170 /* Macro used by computejump()/computematchjump() */
171 #define MIN(a,b) ((a)<(b)?(a):(b))
174 - regcomp - interface for parser and compilation
175 = extern int regcomp(regex_t *, const char *, int);
176 = #define REG_BASIC 0000
177 = #define REG_EXTENDED 0001
178 = #define REG_ICASE 0002
179 = #define REG_NOSUB 0004
180 = #define REG_NEWLINE 0010
181 = #define REG_NOSPEC 0020
182 = #define REG_PEND 0040
183 = #define REG_DUMP 0200
185 int /* 0 success, otherwise REG_something */
186 regcomp(regex_t * __restrict preg,
187 const char * __restrict pattern,
192 struct parse *p = &pa;
197 # define GOODFLAGS(f) (f)
199 # define GOODFLAGS(f) ((f)&~REG_DUMP)
202 cflags = GOODFLAGS(cflags);
203 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
206 if (cflags®_PEND) {
207 if (preg->re_endp < pattern)
209 len = preg->re_endp - pattern;
211 len = strlen((char *)pattern);
213 /* do the mallocs early so failure handling is easy */
214 g = (struct re_guts *)malloc(sizeof(struct re_guts));
218 * Limit the pattern space to avoid a 32-bit overflow on buffer
219 * extension. Also avoid any signed overflow in case of conversion
220 * so make the real limit based on a 31-bit overflow.
222 * Likely not applicable on 64-bit systems but handle the case
223 * generically (who are we to stop people from using ~715MB+
226 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
231 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
232 assert(p->ssize >= len);
234 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
236 if (p->strip == NULL) {
243 p->next = (char *)pattern; /* convenience; we do not modify it */
244 p->end = p->next + len;
247 for (i = 0; i < NPAREN; i++) {
267 g->firststate = THERE();
268 if (cflags®_EXTENDED)
270 else if (cflags®_NOSPEC)
275 g->laststate = THERE();
277 /* tidy up loose ends and fill things in */
280 /* only use Boyer-Moore algorithm if the pattern is bigger
281 * than three characters
285 computematchjumps(p, g);
286 if(g->matchjump == NULL && g->charjump != NULL) {
291 g->nplus = pluscount(p, g);
293 preg->re_nsub = g->nsub;
295 preg->re_magic = MAGIC1;
297 /* not debugging, so can't rely on the assert() in regexec() */
299 SETERROR(REG_ASSERT);
302 /* win or lose, we're done */
303 if (p->error != 0) /* lose */
309 - p_ere - ERE parser top level, concatenation and alternation
310 == static void p_ere(struct parse *p, int stop);
313 p_ere(struct parse *p,
314 int stop) /* character this ERE should end at */
320 int first = 1; /* is this the first alternative? */
323 /* do a bunch of concatenated expressions */
325 while (MORE() && (c = PEEK()) != '|' && c != stop)
327 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
330 break; /* NOTE BREAK OUT */
333 INSERT(OCH_, conc); /* offset is wrong */
338 ASTERN(OOR1, prevback);
340 AHEAD(prevfwd); /* fix previous offset */
342 EMIT(OOR2, 0); /* offset is very wrong */
345 if (!first) { /* tail-end fixups */
347 ASTERN(O_CH, prevback);
350 assert(!MORE() || SEE(stop));
354 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
355 == static void p_ere_exp(struct parse *p);
358 p_ere_exp(struct parse *p)
368 assert(MORE()); /* caller should have ensured this */
374 (void)REQUIRE(MORE(), REG_EPAREN);
378 p->pbegin[subno] = HERE();
379 EMIT(OLPAREN, subno);
382 if (subno < NPAREN) {
383 p->pend[subno] = HERE();
384 assert(p->pend[subno] != 0);
386 EMIT(ORPAREN, subno);
387 (void)MUSTEAT(')', REG_EPAREN);
389 #ifndef POSIX_MISTAKE
390 case ')': /* happens only if no current unmatched ( */
392 * You may ask, why the ifndef? Because I didn't notice
393 * this until slightly too late for 1003.2, and none of the
394 * other 1003.2 regular-expression reviewers noticed it at
395 * all. So an unmatched ) is legal POSIX, at least until
396 * we can get it fixed.
398 SETERROR(REG_EPAREN);
403 p->g->iflags |= USEBOL;
409 p->g->iflags |= USEEOL;
418 SETERROR(REG_BADRPT);
421 if (p->g->cflags®_NEWLINE)
430 (void)REQUIRE(MORE(), REG_EESCAPE);
434 case '{': /* okay as ordinary except if digit follows */
435 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
447 /* we call { a repetition if followed by a digit */
448 if (!( c == '*' || c == '+' || c == '?' ||
449 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
450 return; /* no repetition, we're done */
453 (void)REQUIRE(!wascaret, REG_BADRPT);
455 case '*': /* implemented as +? */
456 /* this case does not require the (y|) trick, noKLUDGE */
459 INSERT(OQUEST_, pos);
460 ASTERN(O_QUEST, pos);
467 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
468 INSERT(OCH_, pos); /* offset slightly wrong */
469 ASTERN(OOR1, pos); /* this one's right */
470 AHEAD(pos); /* fix the OCH_ */
471 EMIT(OOR2, 0); /* offset very wrong... */
472 AHEAD(THERE()); /* ...so fix it */
473 ASTERN(O_CH, THERETHERE());
478 if (isdigit((uch)PEEK())) {
480 (void)REQUIRE(count <= count2, REG_BADBR);
481 } else /* single number with comma */
483 } else /* just a single number */
485 repeat(p, pos, count, count2);
486 if (!EAT('}')) { /* error heuristics */
487 while (MORE() && PEEK() != '}')
489 (void)REQUIRE(MORE(), REG_EBRACE);
498 if (!( c == '*' || c == '+' || c == '?' ||
499 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
501 SETERROR(REG_BADRPT);
505 - p_str - string (no metacharacters) "parser"
506 == static void p_str(struct parse *p);
509 p_str(struct parse *p)
511 (void)REQUIRE(MORE(), REG_EMPTY);
513 ordinary(p, WGETNEXT());
517 - p_bre - BRE parser top level, anchoring and concatenation
518 == static void p_bre(struct parse *p, int end1, \
520 * Giving end1 as OUT essentially eliminates the end1/end2 check.
522 * This implementation is a bit of a kludge, in that a trailing $ is first
523 * taken as an ordinary character and then revised to be an anchor.
524 * The amount of lookahead needed to avoid this kludge is excessive.
527 p_bre(struct parse *p,
528 int end1, /* first terminating character */
529 int end2) /* second terminating character */
531 sopno start = HERE();
532 int first = 1; /* first subexpression? */
537 p->g->iflags |= USEBOL;
540 while (MORE() && !SEETWO(end1, end2)) {
541 wasdollar = p_simp_re(p, first);
544 if (wasdollar) { /* oops, that was a trailing anchor */
547 p->g->iflags |= USEEOL;
551 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
555 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
556 == static int p_simp_re(struct parse *p, int starordinary);
558 static int /* was the simple RE an unbackslashed $? */
559 p_simp_re(struct parse *p,
560 int starordinary) /* is a leading * an ordinary character? */
569 # define BACKSL (1<<CHAR_BIT)
571 pos = HERE(); /* repetion op, if any, covers from here */
573 assert(MORE()); /* caller should have ensured this */
576 (void)REQUIRE(MORE(), REG_EESCAPE);
577 c = BACKSL | GETNEXT();
581 if (p->g->cflags®_NEWLINE)
590 SETERROR(REG_BADRPT);
596 p->pbegin[subno] = HERE();
597 EMIT(OLPAREN, subno);
598 /* the MORE here is an error heuristic */
599 if (MORE() && !SEETWO('\\', ')'))
601 if (subno < NPAREN) {
602 p->pend[subno] = HERE();
603 assert(p->pend[subno] != 0);
605 EMIT(ORPAREN, subno);
606 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
608 case BACKSL|')': /* should not get here -- must be user */
610 SETERROR(REG_EPAREN);
621 i = (c&~BACKSL) - '0';
623 if (p->pend[i] != 0) {
624 assert(i <= p->g->nsub);
626 assert(p->pbegin[i] != 0);
627 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
628 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
629 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
632 SETERROR(REG_ESUBREG);
636 (void)REQUIRE(starordinary, REG_BADRPT);
645 if (EAT('*')) { /* implemented as +? */
646 /* this case does not require the (y|) trick, noKLUDGE */
649 INSERT(OQUEST_, pos);
650 ASTERN(O_QUEST, pos);
651 } else if (EATTWO('\\', '{')) {
654 if (MORE() && isdigit((uch)PEEK())) {
656 (void)REQUIRE(count <= count2, REG_BADBR);
657 } else /* single number with comma */
659 } else /* just a single number */
661 repeat(p, pos, count, count2);
662 if (!EATTWO('\\', '}')) { /* error heuristics */
663 while (MORE() && !SEETWO('\\', '}'))
665 (void)REQUIRE(MORE(), REG_EBRACE);
668 } else if (c == '$') /* $ (but not \$) ends it */
675 - p_count - parse a repetition count
676 == static int p_count(struct parse *p);
678 static int /* the value */
679 p_count(struct parse *p)
684 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
685 count = count*10 + (GETNEXT() - '0');
689 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
694 - p_bracket - parse a bracketed character list
695 == static void p_bracket(struct parse *p);
698 p_bracket(struct parse *p)
703 /* Dept of Truly Sickening Special-Case Kludges */
704 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
709 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
715 if ((cs = allocset(p)) == NULL)
718 if (p->g->cflags®_ICASE)
726 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
730 (void)MUSTEAT(']', REG_EBRACK);
732 if (p->error != 0) /* don't mess things up further */
735 if (cs->invert && p->g->cflags®_NEWLINE)
736 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
738 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
742 EMIT(OANYOF, (int)(cs - p->g->sets));
746 - p_b_term - parse one term of a bracketed character list
747 == static void p_b_term(struct parse *p, cset *cs);
750 p_b_term(struct parse *p, cset *cs)
753 wint_t start, finish;
755 struct xlocale_collate *table =
756 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
758 /* classify what we've got */
759 switch ((MORE()) ? PEEK() : '\0') {
761 c = (MORE2()) ? PEEK2() : '\0';
764 SETERROR(REG_ERANGE);
765 return; /* NOTE RETURN */
772 case ':': /* character class */
774 (void)REQUIRE(MORE(), REG_EBRACK);
776 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
778 (void)REQUIRE(MORE(), REG_EBRACK);
779 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
781 case '=': /* equivalence class */
783 (void)REQUIRE(MORE(), REG_EBRACK);
785 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
787 (void)REQUIRE(MORE(), REG_EBRACK);
788 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
790 default: /* symbol, ordinary character, or range */
791 start = p_b_symbol(p);
792 if (SEE('-') && MORE2() && PEEK2() != ']') {
798 finish = p_b_symbol(p);
804 if (table->__collate_load_error) {
805 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
806 CHaddrange(p, cs, start, finish);
808 (void)REQUIRE(__collate_range_cmp(table, start, finish) <= 0, REG_ERANGE);
809 for (i = 0; i <= UCHAR_MAX; i++) {
810 if ( __collate_range_cmp(table, start, i) <= 0
811 && __collate_range_cmp(table, i, finish) <= 0
822 - p_b_cclass - parse a character-class name and deal with it
823 == static void p_b_cclass(struct parse *p, cset *cs);
826 p_b_cclass(struct parse *p, cset *cs)
833 while (MORE() && isalpha((uch)PEEK()))
836 if (len >= sizeof(clname) - 1) {
837 SETERROR(REG_ECTYPE);
840 memcpy(clname, sp, len);
842 if ((wct = wctype(clname)) == 0) {
843 SETERROR(REG_ECTYPE);
846 CHaddtype(p, cs, wct);
850 - p_b_eclass - parse an equivalence-class name and deal with it
851 == static void p_b_eclass(struct parse *p, cset *cs);
853 * This implementation is incomplete. xxx
856 p_b_eclass(struct parse *p, cset *cs)
860 c = p_b_coll_elem(p, '=');
865 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
866 == static char p_b_symbol(struct parse *p);
868 static wint_t /* value of symbol */
869 p_b_symbol(struct parse *p)
873 (void)REQUIRE(MORE(), REG_EBRACK);
874 if (!EATTWO('[', '.'))
877 /* collating symbol */
878 value = p_b_coll_elem(p, '.');
879 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
884 - p_b_coll_elem - parse a collating-element name and look it up
885 == static char p_b_coll_elem(struct parse *p, int endc);
887 static wint_t /* value of collating element */
888 p_b_coll_elem(struct parse *p,
889 wint_t endc) /* name ended by endc,']' */
898 while (MORE() && !SEETWO(endc, ']'))
901 SETERROR(REG_EBRACK);
905 for (cp = cnames; cp->name != NULL; cp++)
906 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
907 return(cp->code); /* known name */
908 memset(&mbs, 0, sizeof(mbs));
909 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
910 return (wc); /* single character */
911 else if (clen == (size_t)-1 || clen == (size_t)-2)
912 SETERROR(REG_ILLSEQ);
914 SETERROR(REG_ECOLLATE); /* neither */
919 - othercase - return the case counterpart of an alphabetic
920 == static char othercase(int ch);
922 static wint_t /* if no counterpart, return ch */
925 assert(iswalpha(ch));
927 return(towlower(ch));
928 else if (iswlower(ch))
929 return(towupper(ch));
930 else /* peculiar, but could happen */
935 - bothcases - emit a dualcase version of a two-case character
936 == static void bothcases(struct parse *p, int ch);
938 * Boy, is this implementation ever a kludge...
941 bothcases(struct parse *p, wint_t ch)
943 char *oldnext = p->next;
944 char *oldend = p->end;
945 char bracket[3 + MB_LEN_MAX];
949 assert(othercase(ch) != ch); /* p_bracket() would recurse */
951 memset(&mbs, 0, sizeof(mbs));
952 n = wcrtomb(bracket, ch, &mbs);
953 assert(n != (size_t)-1);
955 bracket[n + 1] = '\0';
956 p->end = bracket+n+1;
958 assert(p->next == p->end);
964 - ordinary - emit an ordinary character
965 == static void ordinary(struct parse *p, int ch);
968 ordinary(struct parse *p, wint_t ch)
972 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
974 else if ((ch & OPDMASK) == ch)
978 * Kludge: character is too big to fit into an OCHAR operand.
979 * Emit a singleton set.
981 if ((cs = allocset(p)) == NULL)
984 EMIT(OANYOF, (int)(cs - p->g->sets));
989 - nonnewline - emit REG_NEWLINE version of OANY
990 == static void nonnewline(struct parse *p);
992 * Boy, is this implementation ever a kludge...
995 nonnewline(struct parse *p)
997 char *oldnext = p->next;
998 char *oldend = p->end;
1008 assert(p->next == bracket+3);
1014 - repeat - generate code for a bounded repetition, recursively if needed
1015 == static void repeat(struct parse *p, sopno start, int from, int to);
1018 repeat(struct parse *p,
1019 sopno start, /* operand from here to end of strip */
1020 int from, /* repeated from this number */
1021 int to) /* to this number of times (maybe INFINITY) */
1023 sopno finish = HERE();
1026 # define REP(f, t) ((f)*8 + (t))
1027 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1030 if (p->error != 0) /* head off possible runaway recursion */
1035 switch (REP(MAP(from), MAP(to))) {
1036 case REP(0, 0): /* must be user doing this */
1037 DROP(finish-start); /* drop the operand */
1039 case REP(0, 1): /* as x{1,1}? */
1040 case REP(0, N): /* as x{1,n}? */
1041 case REP(0, INF): /* as x{1,}? */
1042 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1043 INSERT(OCH_, start); /* offset is wrong... */
1044 repeat(p, start+1, 1, to);
1045 ASTERN(OOR1, start);
1046 AHEAD(start); /* ... fix it */
1049 ASTERN(O_CH, THERETHERE());
1051 case REP(1, 1): /* trivial case */
1054 case REP(1, N): /* as x?x{1,n-1} */
1055 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1056 INSERT(OCH_, start);
1057 ASTERN(OOR1, start);
1059 EMIT(OOR2, 0); /* offset very wrong... */
1060 AHEAD(THERE()); /* ...so fix it */
1061 ASTERN(O_CH, THERETHERE());
1062 copy = dupl(p, start+1, finish+1);
1063 assert(copy == finish+4);
1064 repeat(p, copy, 1, to-1);
1066 case REP(1, INF): /* as x+ */
1067 INSERT(OPLUS_, start);
1068 ASTERN(O_PLUS, start);
1070 case REP(N, N): /* as xx{m-1,n-1} */
1071 copy = dupl(p, start, finish);
1072 repeat(p, copy, from-1, to-1);
1074 case REP(N, INF): /* as xx{n-1,INF} */
1075 copy = dupl(p, start, finish);
1076 repeat(p, copy, from-1, to);
1078 default: /* "can't happen" */
1079 SETERROR(REG_ASSERT); /* just in case */
1085 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1086 - character from the parse struct, signals a REG_ILLSEQ error if the
1087 - character can't be converted. Returns the number of bytes consumed.
1090 wgetnext(struct parse *p)
1096 memset(&mbs, 0, sizeof(mbs));
1097 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1098 if (n == (size_t)-1 || n == (size_t)-2) {
1099 SETERROR(REG_ILLSEQ);
1109 - seterr - set an error condition
1110 == static int seterr(struct parse *p, int e);
1112 static int /* useless but makes type checking happy */
1113 seterr(struct parse *p, int e)
1115 if (p->error == 0) /* keep earliest error condition */
1117 p->next = nuls; /* try to bring things to a halt */
1119 return(0); /* make the return value well-defined */
1123 - allocset - allocate a set of characters for []
1124 == static cset *allocset(struct parse *p);
1127 allocset(struct parse *p)
1131 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1133 SETERROR(REG_ESPACE);
1137 cs = &p->g->sets[p->g->ncsets++];
1138 memset(cs, 0, sizeof(*cs));
1144 - freeset - free a now-unused set
1145 == static void freeset(struct parse *p, cset *cs);
1148 freeset(struct parse *p, cset *cs)
1150 cset *top = &p->g->sets[p->g->ncsets];
1155 memset(cs, 0, sizeof(*cs));
1156 if (cs == top-1) /* recover only the easy case */
1161 - singleton - Determine whether a set contains only one character,
1162 - returning it if so, otherwise returning OUT.
1169 for (i = n = 0; i < NC; i++)
1176 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1178 return (cs->wides[0]);
1179 /* Don't bother handling the other cases. */
1184 - CHadd - add character to character set.
1187 CHadd(struct parse *p, cset *cs, wint_t ch)
1189 wint_t nch, *newwides;
1192 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1194 newwides = realloc(cs->wides, (cs->nwides + 1) *
1195 sizeof(*cs->wides));
1196 if (newwides == NULL) {
1197 SETERROR(REG_ESPACE);
1200 cs->wides = newwides;
1201 cs->wides[cs->nwides++] = ch;
1204 if ((nch = towlower(ch)) < NC)
1205 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1206 if ((nch = towupper(ch)) < NC)
1207 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1212 - CHaddrange - add all characters in the range [min,max] to a character set.
1215 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1219 for (; min < NC && min <= max; min++)
1223 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1224 sizeof(*cs->ranges));
1225 if (newranges == NULL) {
1226 SETERROR(REG_ESPACE);
1229 cs->ranges = newranges;
1230 cs->ranges[cs->nranges].min = min;
1231 cs->ranges[cs->nranges].max = max;
1236 - CHaddtype - add all characters of a certain type to a character set.
1239 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1244 for (i = 0; i < NC; i++)
1245 if (iswctype(i, wct))
1247 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1248 sizeof(*cs->types));
1249 if (newtypes == NULL) {
1250 SETERROR(REG_ESPACE);
1253 cs->types = newtypes;
1254 cs->types[cs->ntypes++] = wct;
1258 - dupl - emit a duplicate of a bunch of sops
1259 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1261 static sopno /* start of duplicate */
1262 dupl(struct parse *p,
1263 sopno start, /* from here */
1264 sopno finish) /* to this less one */
1267 sopno len = finish - start;
1269 assert(finish >= start);
1272 enlarge(p, p->ssize + len); /* this many unexpected additions */
1273 assert(p->ssize >= p->slen + len);
1274 (void) memcpy((char *)(p->strip + p->slen),
1275 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1281 - doemit - emit a strip operator
1282 == static void doemit(struct parse *p, sop op, size_t opnd);
1284 * It might seem better to implement this as a macro with a function as
1285 * hard-case backup, but it's just too big and messy unless there are
1286 * some changes to the data structures. Maybe later.
1289 doemit(struct parse *p, sop op, size_t opnd)
1291 /* avoid making error situations worse */
1295 /* deal with oversize operands ("can't happen", more or less) */
1296 assert(opnd < 1<<OPSHIFT);
1298 /* deal with undersized strip */
1299 if (p->slen >= p->ssize)
1300 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1301 assert(p->slen < p->ssize);
1303 /* finally, it's all reduced to the easy case */
1304 p->strip[p->slen++] = SOP(op, opnd);
1308 - doinsert - insert a sop into the strip
1309 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1312 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1318 /* avoid making error situations worse */
1323 EMIT(op, opnd); /* do checks, ensure space */
1324 assert(HERE() == sn+1);
1327 /* adjust paren pointers */
1329 for (i = 1; i < NPAREN; i++) {
1330 if (p->pbegin[i] >= pos) {
1333 if (p->pend[i] >= pos) {
1338 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1339 (HERE()-pos-1)*sizeof(sop));
1344 - dofwd - complete a forward reference
1345 == static void dofwd(struct parse *p, sopno pos, sop value);
1348 dofwd(struct parse *p, sopno pos, sop value)
1350 /* avoid making error situations worse */
1354 assert(value < 1<<OPSHIFT);
1355 p->strip[pos] = OP(p->strip[pos]) | value;
1359 - enlarge - enlarge the strip
1360 == static void enlarge(struct parse *p, sopno size);
1363 enlarge(struct parse *p, sopno size)
1367 if (p->ssize >= size)
1370 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1372 SETERROR(REG_ESPACE);
1380 - stripsnug - compact the strip
1381 == static void stripsnug(struct parse *p, struct re_guts *g);
1384 stripsnug(struct parse *p, struct re_guts *g)
1386 g->nstates = p->slen;
1387 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1388 if (g->strip == NULL) {
1389 SETERROR(REG_ESPACE);
1390 g->strip = p->strip;
1395 - findmust - fill in must and mlen with longest mandatory literal string
1396 == static void findmust(struct parse *p, struct re_guts *g);
1398 * This algorithm could do fancy things like analyzing the operands of |
1399 * for common subsequences. Someday. This code is simple and finds most
1400 * of the interesting cases.
1402 * Note that must and mlen got initialized during setup.
1405 findmust(struct parse *p, struct re_guts *g)
1414 char buf[MB_LEN_MAX];
1418 /* avoid making error situations worse */
1423 * It's not generally safe to do a ``char'' substring search on
1424 * multibyte character strings, but it's safe for at least
1425 * UTF-8 (see RFC 3629).
1427 if (MB_CUR_MAX > 1 &&
1428 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1431 /* find the longest OCHAR sequence in strip */
1435 scan = g->strip + 1;
1439 case OCHAR: /* sequence member */
1440 if (newlen == 0) { /* new sequence */
1441 memset(&mbs, 0, sizeof(mbs));
1442 newstart = scan - 1;
1444 clen = wcrtomb(buf, OPND(s), &mbs);
1445 if (clen == (size_t)-1)
1449 case OPLUS_: /* things that don't break one */
1453 case OQUEST_: /* things that must be skipped */
1455 offset = altoffset(scan, offset);
1460 /* assert() interferes w debug printouts */
1461 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1466 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1468 case OBOW: /* things that break a sequence */
1475 if (newlen > g->mlen) { /* ends one */
1479 g->moffset += offset;
1482 g->moffset = offset;
1490 if (newlen > g->mlen) { /* ends one */
1494 g->moffset += offset;
1497 g->moffset = offset;
1506 case OANYOF: /* may or may not invalidate offset */
1507 /* First, everything as OANY */
1508 if (newlen > g->mlen) { /* ends one */
1512 g->moffset += offset;
1515 g->moffset = offset;
1526 /* Anything here makes it impossible or too hard
1527 * to calculate the offset -- so we give up;
1528 * save the last known good offset, in case the
1529 * must sequence doesn't occur later.
1531 if (newlen > g->mlen) { /* ends one */
1535 g->moffset += offset;
1537 g->moffset = offset;
1543 } while (OP(s) != OEND);
1545 if (g->mlen == 0) { /* there isn't one */
1550 /* turn it into a character string */
1551 g->must = malloc((size_t)g->mlen + 1);
1552 if (g->must == NULL) { /* argh; just forget it */
1559 memset(&mbs, 0, sizeof(mbs));
1560 while (cp < g->must + g->mlen) {
1561 while (OP(s = *scan++) != OCHAR)
1563 clen = wcrtomb(cp, OPND(s), &mbs);
1564 assert(clen != (size_t)-1);
1567 assert(cp == g->must + g->mlen);
1568 *cp++ = '\0'; /* just on general principles */
1572 - altoffset - choose biggest offset among multiple choices
1573 == static int altoffset(sop *scan, int offset);
1575 * Compute, recursively if necessary, the largest offset among multiple
1579 altoffset(sop *scan, int offset)
1585 /* If we gave up already on offsets, return */
1592 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1601 try = altoffset(scan, try);
1608 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1611 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1612 /* We must skip to the next position, or we'll
1613 * leave altoffset() too early.
1639 return largest+offset;
1643 - computejumps - compute char jumps for BM scan
1644 == static void computejumps(struct parse *p, struct re_guts *g);
1646 * This algorithm assumes g->must exists and is has size greater than
1647 * zero. It's based on the algorithm found on Computer Algorithms by
1650 * A char jump is the number of characters one needs to jump based on
1651 * the value of the character from the text that was mismatched.
1654 computejumps(struct parse *p, struct re_guts *g)
1659 /* Avoid making errors worse */
1663 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1664 if (g->charjump == NULL) /* Not a fatal error */
1666 /* Adjust for signed chars, if necessary */
1667 g->charjump = &g->charjump[-(CHAR_MIN)];
1669 /* If the character does not exist in the pattern, the jump
1670 * is equal to the number of characters in the pattern.
1672 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1673 g->charjump[ch] = g->mlen;
1675 /* If the character does exist, compute the jump that would
1676 * take us to the last character in the pattern equal to it
1677 * (notice that we match right to left, so that last character
1678 * is the first one that would be matched).
1680 for (mindex = 0; mindex < g->mlen; mindex++)
1681 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1685 - computematchjumps - compute match jumps for BM scan
1686 == static void computematchjumps(struct parse *p, struct re_guts *g);
1688 * This algorithm assumes g->must exists and is has size greater than
1689 * zero. It's based on the algorithm found on Computer Algorithms by
1692 * A match jump is the number of characters one needs to advance based
1693 * on the already-matched suffix.
1694 * Notice that all values here are minus (g->mlen-1), because of the way
1695 * the search algorithm works.
1698 computematchjumps(struct parse *p, struct re_guts *g)
1700 int mindex; /* General "must" iterator */
1701 int suffix; /* Keeps track of matching suffix */
1702 int ssuffix; /* Keeps track of suffixes' suffix */
1703 int* pmatches; /* pmatches[k] points to the next i
1704 * such that i+1...mlen is a substring
1705 * of k+1...k+mlen-i-1
1708 /* Avoid making errors worse */
1712 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1713 if (pmatches == NULL) {
1714 g->matchjump = NULL;
1718 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1719 if (g->matchjump == NULL) { /* Not a fatal error */
1724 /* Set maximum possible jump for each character in the pattern */
1725 for (mindex = 0; mindex < g->mlen; mindex++)
1726 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1728 /* Compute pmatches[] */
1729 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1730 mindex--, suffix--) {
1731 pmatches[mindex] = suffix;
1733 /* If a mismatch is found, interrupting the substring,
1734 * compute the matchjump for that position. If no
1735 * mismatch is found, then a text substring mismatched
1736 * against the suffix will also mismatch against the
1739 while (suffix < g->mlen
1740 && g->must[mindex] != g->must[suffix]) {
1741 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1742 g->mlen - mindex - 1);
1743 suffix = pmatches[suffix];
1747 /* Compute the matchjump up to the last substring found to jump
1748 * to the beginning of the largest must pattern prefix matching
1751 for (mindex = 0; mindex <= suffix; mindex++)
1752 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1753 g->mlen + suffix - mindex);
1755 ssuffix = pmatches[suffix];
1756 while (suffix < g->mlen) {
1757 while (suffix <= ssuffix && suffix < g->mlen) {
1758 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1759 g->mlen + ssuffix - suffix);
1762 if (suffix < g->mlen)
1763 ssuffix = pmatches[ssuffix];
1770 - pluscount - count + nesting
1771 == static sopno pluscount(struct parse *p, struct re_guts *g);
1773 static sopno /* nesting depth */
1774 pluscount(struct parse *p, struct re_guts *g)
1782 return(0); /* there may not be an OEND */
1784 scan = g->strip + 1;
1792 if (plusnest > maxnest)
1797 } while (OP(s) != OEND);