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);
458 /* we call { a repetition if followed by a digit */
459 if (!( c == '*' || c == '+' || c == '?' ||
460 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
461 return; /* no repetition, we're done */
464 (void)REQUIRE(!wascaret, REG_BADRPT);
466 case '*': /* implemented as +? */
467 /* this case does not require the (y|) trick, noKLUDGE */
470 INSERT(OQUEST_, pos);
471 ASTERN(O_QUEST, pos);
478 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
479 INSERT(OCH_, pos); /* offset slightly wrong */
480 ASTERN(OOR1, pos); /* this one's right */
481 AHEAD(pos); /* fix the OCH_ */
482 EMIT(OOR2, 0); /* offset very wrong... */
483 AHEAD(THERE()); /* ...so fix it */
484 ASTERN(O_CH, THERETHERE());
489 if (isdigit((uch)PEEK())) {
491 (void)REQUIRE(count <= count2, REG_BADBR);
492 } else /* single number with comma */
494 } else /* just a single number */
496 repeat(p, pos, count, count2);
497 if (!EAT('}')) { /* error heuristics */
498 while (MORE() && PEEK() != '}')
500 (void)REQUIRE(MORE(), REG_EBRACE);
509 if (!( c == '*' || c == '+' || c == '?' ||
510 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
512 SETERROR(REG_BADRPT);
516 - p_str - string (no metacharacters) "parser"
517 == static void p_str(struct parse *p);
520 p_str(struct parse *p)
522 (void)REQUIRE(MORE(), REG_EMPTY);
524 ordinary(p, WGETNEXT());
528 - p_bre - BRE parser top level, anchoring and concatenation
529 == static void p_bre(struct parse *p, int end1, \
531 * Giving end1 as OUT essentially eliminates the end1/end2 check.
533 * This implementation is a bit of a kludge, in that a trailing $ is first
534 * taken as an ordinary character and then revised to be an anchor.
535 * The amount of lookahead needed to avoid this kludge is excessive.
538 p_bre(struct parse *p,
539 int end1, /* first terminating character */
540 int end2) /* second terminating character */
542 sopno start = HERE();
543 int first = 1; /* first subexpression? */
548 p->g->iflags |= USEBOL;
551 while (MORE() && !SEETWO(end1, end2)) {
552 wasdollar = p_simp_re(p, first);
555 if (wasdollar) { /* oops, that was a trailing anchor */
558 p->g->iflags |= USEEOL;
562 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
566 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
567 == static int p_simp_re(struct parse *p, int starordinary);
569 static int /* was the simple RE an unbackslashed $? */
570 p_simp_re(struct parse *p,
571 int starordinary) /* is a leading * an ordinary character? */
580 # define BACKSL (1<<CHAR_BIT)
582 pos = HERE(); /* repetion op, if any, covers from here */
584 assert(MORE()); /* caller should have ensured this */
587 (void)REQUIRE(MORE(), REG_EESCAPE);
588 c = BACKSL | GETNEXT();
592 if (p->g->cflags®_NEWLINE)
607 SETERROR(REG_BADRPT);
613 p->pbegin[subno] = HERE();
614 EMIT(OLPAREN, subno);
615 /* the MORE here is an error heuristic */
616 if (MORE() && !SEETWO('\\', ')'))
618 if (subno < NPAREN) {
619 p->pend[subno] = HERE();
620 assert(p->pend[subno] != 0);
622 EMIT(ORPAREN, subno);
623 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
625 case BACKSL|')': /* should not get here -- must be user */
627 SETERROR(REG_EPAREN);
638 i = (c&~BACKSL) - '0';
640 if (p->pend[i] != 0) {
641 assert(i <= p->g->nsub);
643 assert(p->pbegin[i] != 0);
644 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
645 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
646 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
649 SETERROR(REG_ESUBREG);
653 (void)REQUIRE(starordinary, REG_BADRPT);
657 return(0); /* Definitely not $... */
664 if (EAT('*')) { /* implemented as +? */
665 /* this case does not require the (y|) trick, noKLUDGE */
668 INSERT(OQUEST_, pos);
669 ASTERN(O_QUEST, pos);
670 } else if (EATTWO('\\', '{')) {
673 if (MORE() && isdigit((uch)PEEK())) {
675 (void)REQUIRE(count <= count2, REG_BADBR);
676 } else /* single number with comma */
678 } else /* just a single number */
680 repeat(p, pos, count, count2);
681 if (!EATTWO('\\', '}')) { /* error heuristics */
682 while (MORE() && !SEETWO('\\', '}'))
684 (void)REQUIRE(MORE(), REG_EBRACE);
687 } else if (c == '$') /* $ (but not \$) ends it */
694 - p_count - parse a repetition count
695 == static int p_count(struct parse *p);
697 static int /* the value */
698 p_count(struct parse *p)
703 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
704 count = count*10 + (GETNEXT() - '0');
708 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
713 - p_bracket - parse a bracketed character list
714 == static void p_bracket(struct parse *p);
717 p_bracket(struct parse *p)
722 /* Dept of Truly Sickening Special-Case Kludges */
723 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
728 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
734 if ((cs = allocset(p)) == NULL)
737 if (p->g->cflags®_ICASE)
745 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
749 (void)MUSTEAT(']', REG_EBRACK);
751 if (p->error != 0) /* don't mess things up further */
754 if (cs->invert && p->g->cflags®_NEWLINE)
755 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
757 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
761 EMIT(OANYOF, (int)(cs - p->g->sets));
765 - p_b_term - parse one term of a bracketed character list
766 == static void p_b_term(struct parse *p, cset *cs);
769 p_b_term(struct parse *p, cset *cs)
772 wint_t start, finish;
774 struct xlocale_collate *table =
775 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
777 /* classify what we've got */
778 switch ((MORE()) ? PEEK() : '\0') {
780 c = (MORE2()) ? PEEK2() : '\0';
783 SETERROR(REG_ERANGE);
784 return; /* NOTE RETURN */
791 case ':': /* character class */
793 (void)REQUIRE(MORE(), REG_EBRACK);
795 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
797 (void)REQUIRE(MORE(), REG_EBRACK);
798 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
800 case '=': /* equivalence class */
802 (void)REQUIRE(MORE(), REG_EBRACK);
804 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
806 (void)REQUIRE(MORE(), REG_EBRACK);
807 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
809 default: /* symbol, ordinary character, or range */
810 start = p_b_symbol(p);
811 if (SEE('-') && MORE2() && PEEK2() != ']') {
817 finish = p_b_symbol(p);
823 if (table->__collate_load_error || MB_CUR_MAX > 1) {
824 (void)REQUIRE(start <= finish, REG_ERANGE);
825 CHaddrange(p, cs, start, finish);
827 (void)REQUIRE(__wcollate_range_cmp(start, finish) <= 0, REG_ERANGE);
828 for (i = 0; i <= UCHAR_MAX; i++) {
829 if ( __wcollate_range_cmp(start, i) <= 0
830 && __wcollate_range_cmp(i, finish) <= 0
841 - p_b_cclass - parse a character-class name and deal with it
842 == static void p_b_cclass(struct parse *p, cset *cs);
845 p_b_cclass(struct parse *p, cset *cs)
852 while (MORE() && isalpha((uch)PEEK()))
855 if (len >= sizeof(clname) - 1) {
856 SETERROR(REG_ECTYPE);
859 memcpy(clname, sp, len);
861 if ((wct = wctype(clname)) == 0) {
862 SETERROR(REG_ECTYPE);
865 CHaddtype(p, cs, wct);
869 - p_b_eclass - parse an equivalence-class name and deal with it
870 == static void p_b_eclass(struct parse *p, cset *cs);
872 * This implementation is incomplete. xxx
875 p_b_eclass(struct parse *p, cset *cs)
879 c = p_b_coll_elem(p, '=');
884 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
885 == static wint_t p_b_symbol(struct parse *p);
887 static wint_t /* value of symbol */
888 p_b_symbol(struct parse *p)
892 (void)REQUIRE(MORE(), REG_EBRACK);
893 if (!EATTWO('[', '.'))
896 /* collating symbol */
897 value = p_b_coll_elem(p, '.');
898 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
903 - p_b_coll_elem - parse a collating-element name and look it up
904 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
906 static wint_t /* value of collating element */
907 p_b_coll_elem(struct parse *p,
908 wint_t endc) /* name ended by endc,']' */
917 while (MORE() && !SEETWO(endc, ']'))
920 SETERROR(REG_EBRACK);
924 for (cp = cnames; cp->name != NULL; cp++)
925 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
926 return(cp->code); /* known name */
927 memset(&mbs, 0, sizeof(mbs));
928 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
929 return (wc); /* single character */
930 else if (clen == (size_t)-1 || clen == (size_t)-2)
931 SETERROR(REG_ILLSEQ);
933 SETERROR(REG_ECOLLATE); /* neither */
938 - othercase - return the case counterpart of an alphabetic
939 == static wint_t othercase(wint_t ch);
941 static wint_t /* if no counterpart, return ch */
944 assert(iswalpha(ch));
946 return(towlower(ch));
947 else if (iswlower(ch))
948 return(towupper(ch));
949 else /* peculiar, but could happen */
954 - bothcases - emit a dualcase version of a two-case character
955 == static void bothcases(struct parse *p, wint_t ch);
957 * Boy, is this implementation ever a kludge...
960 bothcases(struct parse *p, wint_t ch)
962 char *oldnext = p->next;
963 char *oldend = p->end;
964 char bracket[3 + MB_LEN_MAX];
968 assert(othercase(ch) != ch); /* p_bracket() would recurse */
970 memset(&mbs, 0, sizeof(mbs));
971 n = wcrtomb(bracket, ch, &mbs);
972 assert(n != (size_t)-1);
974 bracket[n + 1] = '\0';
975 p->end = bracket+n+1;
977 assert(p->next == p->end);
983 - ordinary - emit an ordinary character
984 == static void ordinary(struct parse *p, wint_t ch);
987 ordinary(struct parse *p, wint_t ch)
991 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
993 else if ((ch & OPDMASK) == ch)
997 * Kludge: character is too big to fit into an OCHAR operand.
998 * Emit a singleton set.
1000 if ((cs = allocset(p)) == NULL)
1003 EMIT(OANYOF, (int)(cs - p->g->sets));
1008 - nonnewline - emit REG_NEWLINE version of OANY
1009 == static void nonnewline(struct parse *p);
1011 * Boy, is this implementation ever a kludge...
1014 nonnewline(struct parse *p)
1016 char *oldnext = p->next;
1017 char *oldend = p->end;
1027 assert(p->next == bracket+3);
1033 - repeat - generate code for a bounded repetition, recursively if needed
1034 == static void repeat(struct parse *p, sopno start, int from, int to);
1037 repeat(struct parse *p,
1038 sopno start, /* operand from here to end of strip */
1039 int from, /* repeated from this number */
1040 int to) /* to this number of times (maybe INFINITY) */
1042 sopno finish = HERE();
1045 # define REP(f, t) ((f)*8 + (t))
1046 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1049 if (p->error != 0) /* head off possible runaway recursion */
1054 switch (REP(MAP(from), MAP(to))) {
1055 case REP(0, 0): /* must be user doing this */
1056 DROP(finish-start); /* drop the operand */
1058 case REP(0, 1): /* as x{1,1}? */
1059 case REP(0, N): /* as x{1,n}? */
1060 case REP(0, INF): /* as x{1,}? */
1061 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1062 INSERT(OCH_, start); /* offset is wrong... */
1063 repeat(p, start+1, 1, to);
1064 ASTERN(OOR1, start);
1065 AHEAD(start); /* ... fix it */
1068 ASTERN(O_CH, THERETHERE());
1070 case REP(1, 1): /* trivial case */
1073 case REP(1, N): /* as x?x{1,n-1} */
1074 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1075 INSERT(OCH_, start);
1076 ASTERN(OOR1, start);
1078 EMIT(OOR2, 0); /* offset very wrong... */
1079 AHEAD(THERE()); /* ...so fix it */
1080 ASTERN(O_CH, THERETHERE());
1081 copy = dupl(p, start+1, finish+1);
1082 assert(copy == finish+4);
1083 repeat(p, copy, 1, to-1);
1085 case REP(1, INF): /* as x+ */
1086 INSERT(OPLUS_, start);
1087 ASTERN(O_PLUS, start);
1089 case REP(N, N): /* as xx{m-1,n-1} */
1090 copy = dupl(p, start, finish);
1091 repeat(p, copy, from-1, to-1);
1093 case REP(N, INF): /* as xx{n-1,INF} */
1094 copy = dupl(p, start, finish);
1095 repeat(p, copy, from-1, to);
1097 default: /* "can't happen" */
1098 SETERROR(REG_ASSERT); /* just in case */
1104 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1105 - character from the parse struct, signals a REG_ILLSEQ error if the
1106 - character can't be converted. Returns the number of bytes consumed.
1109 wgetnext(struct parse *p)
1115 memset(&mbs, 0, sizeof(mbs));
1116 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1117 if (n == (size_t)-1 || n == (size_t)-2) {
1118 SETERROR(REG_ILLSEQ);
1128 - seterr - set an error condition
1129 == static int seterr(struct parse *p, int e);
1131 static int /* useless but makes type checking happy */
1132 seterr(struct parse *p, int e)
1134 if (p->error == 0) /* keep earliest error condition */
1136 p->next = nuls; /* try to bring things to a halt */
1138 return(0); /* make the return value well-defined */
1142 - allocset - allocate a set of characters for []
1143 == static cset *allocset(struct parse *p);
1146 allocset(struct parse *p)
1150 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1152 SETERROR(REG_ESPACE);
1156 cs = &p->g->sets[p->g->ncsets++];
1157 memset(cs, 0, sizeof(*cs));
1163 - freeset - free a now-unused set
1164 == static void freeset(struct parse *p, cset *cs);
1167 freeset(struct parse *p, cset *cs)
1169 cset *top = &p->g->sets[p->g->ncsets];
1174 memset(cs, 0, sizeof(*cs));
1175 if (cs == top-1) /* recover only the easy case */
1180 - singleton - Determine whether a set contains only one character,
1181 - returning it if so, otherwise returning OUT.
1188 for (i = n = 0; i < NC; i++)
1195 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1197 return (cs->wides[0]);
1198 /* Don't bother handling the other cases. */
1203 - CHadd - add character to character set.
1206 CHadd(struct parse *p, cset *cs, wint_t ch)
1208 wint_t nch, *newwides;
1211 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1213 newwides = realloc(cs->wides, (cs->nwides + 1) *
1214 sizeof(*cs->wides));
1215 if (newwides == NULL) {
1216 SETERROR(REG_ESPACE);
1219 cs->wides = newwides;
1220 cs->wides[cs->nwides++] = ch;
1223 if ((nch = towlower(ch)) < NC)
1224 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1225 if ((nch = towupper(ch)) < NC)
1226 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1231 - CHaddrange - add all characters in the range [min,max] to a character set.
1234 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1238 for (; min < NC && min <= max; min++)
1242 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1243 sizeof(*cs->ranges));
1244 if (newranges == NULL) {
1245 SETERROR(REG_ESPACE);
1248 cs->ranges = newranges;
1249 cs->ranges[cs->nranges].min = min;
1250 cs->ranges[cs->nranges].max = max;
1255 - CHaddtype - add all characters of a certain type to a character set.
1258 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1263 for (i = 0; i < NC; i++)
1264 if (iswctype(i, wct))
1266 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1267 sizeof(*cs->types));
1268 if (newtypes == NULL) {
1269 SETERROR(REG_ESPACE);
1272 cs->types = newtypes;
1273 cs->types[cs->ntypes++] = wct;
1277 - dupl - emit a duplicate of a bunch of sops
1278 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1280 static sopno /* start of duplicate */
1281 dupl(struct parse *p,
1282 sopno start, /* from here */
1283 sopno finish) /* to this less one */
1286 sopno len = finish - start;
1288 assert(finish >= start);
1291 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1293 (void) memcpy((char *)(p->strip + p->slen),
1294 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1300 - doemit - emit a strip operator
1301 == static void doemit(struct parse *p, sop op, size_t opnd);
1303 * It might seem better to implement this as a macro with a function as
1304 * hard-case backup, but it's just too big and messy unless there are
1305 * some changes to the data structures. Maybe later.
1308 doemit(struct parse *p, sop op, size_t opnd)
1310 /* avoid making error situations worse */
1314 /* deal with oversize operands ("can't happen", more or less) */
1315 assert(opnd < 1<<OPSHIFT);
1317 /* deal with undersized strip */
1318 if (p->slen >= p->ssize)
1319 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1322 /* finally, it's all reduced to the easy case */
1323 p->strip[p->slen++] = SOP(op, opnd);
1327 - doinsert - insert a sop into the strip
1328 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1331 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1337 /* avoid making error situations worse */
1342 EMIT(op, opnd); /* do checks, ensure space */
1343 assert(HERE() == sn+1);
1346 /* adjust paren pointers */
1348 for (i = 1; i < NPAREN; i++) {
1349 if (p->pbegin[i] >= pos) {
1352 if (p->pend[i] >= pos) {
1357 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1358 (HERE()-pos-1)*sizeof(sop));
1363 - dofwd - complete a forward reference
1364 == static void dofwd(struct parse *p, sopno pos, sop value);
1367 dofwd(struct parse *p, sopno pos, sop value)
1369 /* avoid making error situations worse */
1373 assert(value < 1<<OPSHIFT);
1374 p->strip[pos] = OP(p->strip[pos]) | value;
1378 - enlarge - enlarge the strip
1379 == static int enlarge(struct parse *p, sopno size);
1382 enlarge(struct parse *p, sopno size)
1386 if (p->ssize >= size)
1389 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1391 SETERROR(REG_ESPACE);
1400 - stripsnug - compact the strip
1401 == static void stripsnug(struct parse *p, struct re_guts *g);
1404 stripsnug(struct parse *p, struct re_guts *g)
1406 g->nstates = p->slen;
1407 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1408 if (g->strip == NULL) {
1409 SETERROR(REG_ESPACE);
1410 g->strip = p->strip;
1415 - findmust - fill in must and mlen with longest mandatory literal string
1416 == static void findmust(struct parse *p, struct re_guts *g);
1418 * This algorithm could do fancy things like analyzing the operands of |
1419 * for common subsequences. Someday. This code is simple and finds most
1420 * of the interesting cases.
1422 * Note that must and mlen got initialized during setup.
1425 findmust(struct parse *p, struct re_guts *g)
1434 char buf[MB_LEN_MAX];
1438 /* avoid making error situations worse */
1443 * It's not generally safe to do a ``char'' substring search on
1444 * multibyte character strings, but it's safe for at least
1445 * UTF-8 (see RFC 3629).
1447 if (MB_CUR_MAX > 1 &&
1448 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1451 /* find the longest OCHAR sequence in strip */
1455 scan = g->strip + 1;
1459 case OCHAR: /* sequence member */
1460 if (newlen == 0) { /* new sequence */
1461 memset(&mbs, 0, sizeof(mbs));
1462 newstart = scan - 1;
1464 clen = wcrtomb(buf, OPND(s), &mbs);
1465 if (clen == (size_t)-1)
1469 case OPLUS_: /* things that don't break one */
1473 case OQUEST_: /* things that must be skipped */
1475 offset = altoffset(scan, offset);
1480 /* assert() interferes w debug printouts */
1481 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1486 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1488 case OBOW: /* things that break a sequence */
1495 if (newlen > g->mlen) { /* ends one */
1499 g->moffset += offset;
1502 g->moffset = offset;
1510 if (newlen > g->mlen) { /* ends one */
1514 g->moffset += offset;
1517 g->moffset = offset;
1526 case OANYOF: /* may or may not invalidate offset */
1527 /* First, everything as OANY */
1528 if (newlen > g->mlen) { /* ends one */
1532 g->moffset += offset;
1535 g->moffset = offset;
1546 /* Anything here makes it impossible or too hard
1547 * to calculate the offset -- so we give up;
1548 * save the last known good offset, in case the
1549 * must sequence doesn't occur later.
1551 if (newlen > g->mlen) { /* ends one */
1555 g->moffset += offset;
1557 g->moffset = offset;
1563 } while (OP(s) != OEND);
1565 if (g->mlen == 0) { /* there isn't one */
1570 /* turn it into a character string */
1571 g->must = malloc((size_t)g->mlen + 1);
1572 if (g->must == NULL) { /* argh; just forget it */
1579 memset(&mbs, 0, sizeof(mbs));
1580 while (cp < g->must + g->mlen) {
1581 while (OP(s = *scan++) != OCHAR)
1583 clen = wcrtomb(cp, OPND(s), &mbs);
1584 assert(clen != (size_t)-1);
1587 assert(cp == g->must + g->mlen);
1588 *cp++ = '\0'; /* just on general principles */
1592 - altoffset - choose biggest offset among multiple choices
1593 == static int altoffset(sop *scan, int offset);
1595 * Compute, recursively if necessary, the largest offset among multiple
1599 altoffset(sop *scan, int offset)
1605 /* If we gave up already on offsets, return */
1612 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1621 try = altoffset(scan, try);
1628 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1631 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1632 /* We must skip to the next position, or we'll
1633 * leave altoffset() too early.
1659 return largest+offset;
1663 - computejumps - compute char jumps for BM scan
1664 == static void computejumps(struct parse *p, struct re_guts *g);
1666 * This algorithm assumes g->must exists and is has size greater than
1667 * zero. It's based on the algorithm found on Computer Algorithms by
1670 * A char jump is the number of characters one needs to jump based on
1671 * the value of the character from the text that was mismatched.
1674 computejumps(struct parse *p, struct re_guts *g)
1679 /* Avoid making errors worse */
1683 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1684 if (g->charjump == NULL) /* Not a fatal error */
1686 /* Adjust for signed chars, if necessary */
1687 g->charjump = &g->charjump[-(CHAR_MIN)];
1689 /* If the character does not exist in the pattern, the jump
1690 * is equal to the number of characters in the pattern.
1692 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1693 g->charjump[ch] = g->mlen;
1695 /* If the character does exist, compute the jump that would
1696 * take us to the last character in the pattern equal to it
1697 * (notice that we match right to left, so that last character
1698 * is the first one that would be matched).
1700 for (mindex = 0; mindex < g->mlen; mindex++)
1701 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1705 - computematchjumps - compute match jumps for BM scan
1706 == static void computematchjumps(struct parse *p, struct re_guts *g);
1708 * This algorithm assumes g->must exists and is has size greater than
1709 * zero. It's based on the algorithm found on Computer Algorithms by
1712 * A match jump is the number of characters one needs to advance based
1713 * on the already-matched suffix.
1714 * Notice that all values here are minus (g->mlen-1), because of the way
1715 * the search algorithm works.
1718 computematchjumps(struct parse *p, struct re_guts *g)
1720 int mindex; /* General "must" iterator */
1721 int suffix; /* Keeps track of matching suffix */
1722 int ssuffix; /* Keeps track of suffixes' suffix */
1723 int* pmatches; /* pmatches[k] points to the next i
1724 * such that i+1...mlen is a substring
1725 * of k+1...k+mlen-i-1
1728 /* Avoid making errors worse */
1732 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1733 if (pmatches == NULL) {
1734 g->matchjump = NULL;
1738 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1739 if (g->matchjump == NULL) { /* Not a fatal error */
1744 /* Set maximum possible jump for each character in the pattern */
1745 for (mindex = 0; mindex < g->mlen; mindex++)
1746 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1748 /* Compute pmatches[] */
1749 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1750 mindex--, suffix--) {
1751 pmatches[mindex] = suffix;
1753 /* If a mismatch is found, interrupting the substring,
1754 * compute the matchjump for that position. If no
1755 * mismatch is found, then a text substring mismatched
1756 * against the suffix will also mismatch against the
1759 while (suffix < g->mlen
1760 && g->must[mindex] != g->must[suffix]) {
1761 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1762 g->mlen - mindex - 1);
1763 suffix = pmatches[suffix];
1767 /* Compute the matchjump up to the last substring found to jump
1768 * to the beginning of the largest must pattern prefix matching
1771 for (mindex = 0; mindex <= suffix; mindex++)
1772 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1773 g->mlen + suffix - mindex);
1775 ssuffix = pmatches[suffix];
1776 while (suffix < g->mlen) {
1777 while (suffix <= ssuffix && suffix < g->mlen) {
1778 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1779 g->mlen + ssuffix - suffix);
1782 if (suffix < g->mlen)
1783 ssuffix = pmatches[ssuffix];
1790 - pluscount - count + nesting
1791 == static sopno pluscount(struct parse *p, struct re_guts *g);
1793 static sopno /* nesting depth */
1794 pluscount(struct parse *p, struct re_guts *g)
1802 return(0); /* there may not be an OEND */
1804 scan = g->strip + 1;
1812 if (plusnest > maxnest)
1817 } while (OP(s) != OEND);