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 * 3. 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
39 * $FreeBSD: head/lib/libc/regex/regcomp.c 247596 2013-03-01 23:26:13Z delphij $
41 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
44 #include <sys/types.h>
63 * parse structure, passed up and down to avoid global variables and
67 char *next; /* next character in RE */
68 char *end; /* end of string (-> NUL normally) */
69 int error; /* has an error been seen? */
70 sop *strip; /* malloced strip */
71 sopno ssize; /* malloced strip size (allocated) */
72 sopno slen; /* malloced strip length (used) */
73 int ncsalloc; /* number of csets allocated */
75 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
76 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
77 sopno pend[NPAREN]; /* -> ) ([0] unused) */
80 /* ========= begin header generated by ./mkh ========= */
85 /* === regcomp.c === */
86 static void p_ere(struct parse *p, int stop);
87 static void p_ere_exp(struct parse *p);
88 static void p_str(struct parse *p);
89 static void p_bre(struct parse *p, int end1, int end2);
90 static int p_simp_re(struct parse *p, int starordinary);
91 static int p_count(struct parse *p);
92 static void p_bracket(struct parse *p);
93 static void p_b_term(struct parse *p, cset *cs);
94 static void p_b_cclass(struct parse *p, cset *cs);
95 static void p_b_eclass(struct parse *p, cset *cs);
96 static wint_t p_b_symbol(struct parse *p);
97 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
98 static wint_t othercase(wint_t ch);
99 static void bothcases(struct parse *p, wint_t ch);
100 static void ordinary(struct parse *p, wint_t ch);
101 static void nonnewline(struct parse *p);
102 static void repeat(struct parse *p, sopno start, int from, int to);
103 static int seterr(struct parse *p, int e);
104 static cset *allocset(struct parse *p);
105 static void freeset(struct parse *p, cset *cs);
106 static void CHadd(struct parse *p, cset *cs, wint_t ch);
107 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
108 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
109 static wint_t singleton(cset *cs);
110 static sopno dupl(struct parse *p, sopno start, sopno finish);
111 static void doemit(struct parse *p, sop op, size_t opnd);
112 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
113 static void dofwd(struct parse *p, sopno pos, sop value);
114 static int enlarge(struct parse *p, sopno size);
115 static void stripsnug(struct parse *p, struct re_guts *g);
116 static void findmust(struct parse *p, struct re_guts *g);
117 static int altoffset(sop *scan, int offset);
118 static void computejumps(struct parse *p, struct re_guts *g);
119 static void computematchjumps(struct parse *p, struct re_guts *g);
120 static sopno pluscount(struct parse *p, struct re_guts *g);
121 static wint_t wgetnext(struct parse *p);
126 /* ========= end header generated by ./mkh ========= */
128 static char nuls[10]; /* place to point scanner in event of error */
131 * macros for use with parse structure
132 * BEWARE: these know that the parse structure is named `p' !!!
134 #define PEEK() (*p->next)
135 #define PEEK2() (*(p->next+1))
136 #define MORE() (p->next < p->end)
137 #define MORE2() (p->next+1 < p->end)
138 #define SEE(c) (MORE() && PEEK() == (c))
139 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
140 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
141 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
142 #define NEXT() (p->next++)
143 #define NEXT2() (p->next += 2)
144 #define NEXTn(n) (p->next += (n))
145 #define GETNEXT() (*p->next++)
146 #define WGETNEXT() wgetnext(p)
147 #define SETERROR(e) seterr(p, (e))
148 #define REQUIRE(co, e) ((co) || SETERROR(e))
149 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
150 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
151 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
152 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
153 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
154 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
155 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
156 #define HERE() (p->slen)
157 #define THERE() (p->slen - 1)
158 #define THERETHERE() (p->slen - 2)
159 #define DROP(n) (p->slen -= (n))
162 static int never = 0; /* for use in asserts; shuts lint up */
164 #define never 0 /* some <assert.h>s have bugs too */
167 /* Macro used by computejump()/computematchjump() */
168 #define MIN(a,b) ((a)<(b)?(a):(b))
171 - regcomp - interface for parser and compilation
172 = extern int regcomp(regex_t *, const char *, int);
173 = #define REG_BASIC 0000
174 = #define REG_EXTENDED 0001
175 = #define REG_ICASE 0002
176 = #define REG_NOSUB 0004
177 = #define REG_NEWLINE 0010
178 = #define REG_NOSPEC 0020
179 = #define REG_PEND 0040
180 = #define REG_DUMP 0200
182 int /* 0 success, otherwise REG_something */
183 regcomp(regex_t * __restrict preg,
184 const char * __restrict pattern,
189 struct parse *p = &pa;
193 # define GOODFLAGS(f) (f)
195 # define GOODFLAGS(f) ((f)&~REG_DUMP)
198 cflags = GOODFLAGS(cflags);
199 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
202 if (cflags®_PEND) {
203 if (preg->re_endp < pattern)
205 len = preg->re_endp - pattern;
207 len = strlen((char *)pattern);
209 /* do the mallocs early so failure handling is easy */
210 g = (struct re_guts *)malloc(sizeof(struct re_guts));
213 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
214 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
216 if (p->strip == NULL) {
223 p->next = (char *)pattern; /* convenience; we do not modify it */
224 p->end = p->next + len;
227 for (i = 0; i < NPAREN; i++) {
247 g->firststate = THERE();
248 if (cflags®_EXTENDED)
250 else if (cflags®_NOSPEC)
255 g->laststate = THERE();
257 /* tidy up loose ends and fill things in */
260 /* only use Boyer-Moore algorithm if the pattern is bigger
261 * than three characters
265 computematchjumps(p, g);
266 if(g->matchjump == NULL && g->charjump != NULL) {
271 g->nplus = pluscount(p, g);
273 preg->re_nsub = g->nsub;
275 preg->re_magic = MAGIC1;
277 /* not debugging, so can't rely on the assert() in regexec() */
279 SETERROR(REG_ASSERT);
282 /* win or lose, we're done */
283 if (p->error != 0) /* lose */
289 - p_ere - ERE parser top level, concatenation and alternation
290 == static void p_ere(struct parse *p, int_t stop);
293 p_ere(struct parse *p,
294 int stop) /* character this ERE should end at */
300 int first = 1; /* is this the first alternative? */
303 /* do a bunch of concatenated expressions */
305 while (MORE() && (c = PEEK()) != '|' && c != stop)
307 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
310 break; /* NOTE BREAK OUT */
313 INSERT(OCH_, conc); /* offset is wrong */
318 ASTERN(OOR1, prevback);
320 AHEAD(prevfwd); /* fix previous offset */
322 EMIT(OOR2, 0); /* offset is very wrong */
325 if (!first) { /* tail-end fixups */
327 ASTERN(O_CH, prevback);
330 assert(!MORE() || SEE(stop));
334 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
335 == static void p_ere_exp(struct parse *p);
338 p_ere_exp(struct parse *p)
348 assert(MORE()); /* caller should have ensured this */
354 (void)REQUIRE(MORE(), REG_EPAREN);
358 p->pbegin[subno] = HERE();
359 EMIT(OLPAREN, subno);
362 if (subno < NPAREN) {
363 p->pend[subno] = HERE();
364 assert(p->pend[subno] != 0);
366 EMIT(ORPAREN, subno);
367 (void)MUSTEAT(')', REG_EPAREN);
369 #ifndef POSIX_MISTAKE
370 case ')': /* happens only if no current unmatched ( */
372 * You may ask, why the ifndef? Because I didn't notice
373 * this until slightly too late for 1003.2, and none of the
374 * other 1003.2 regular-expression reviewers noticed it at
375 * all. So an unmatched ) is legal POSIX, at least until
376 * we can get it fixed.
378 SETERROR(REG_EPAREN);
383 p->g->iflags |= USEBOL;
389 p->g->iflags |= USEEOL;
398 SETERROR(REG_BADRPT);
401 if (p->g->cflags®_NEWLINE)
410 (void)REQUIRE(MORE(), REG_EESCAPE);
414 case '{': /* okay as ordinary except if digit follows */
415 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
427 /* we call { a repetition if followed by a digit */
428 if (!( c == '*' || c == '+' || c == '?' ||
429 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
430 return; /* no repetition, we're done */
433 (void)REQUIRE(!wascaret, REG_BADRPT);
435 case '*': /* implemented as +? */
436 /* this case does not require the (y|) trick, noKLUDGE */
439 INSERT(OQUEST_, pos);
440 ASTERN(O_QUEST, pos);
447 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
448 INSERT(OCH_, pos); /* offset slightly wrong */
449 ASTERN(OOR1, pos); /* this one's right */
450 AHEAD(pos); /* fix the OCH_ */
451 EMIT(OOR2, 0); /* offset very wrong... */
452 AHEAD(THERE()); /* ...so fix it */
453 ASTERN(O_CH, THERETHERE());
458 if (isdigit((uch)PEEK())) {
460 (void)REQUIRE(count <= count2, REG_BADBR);
461 } else /* single number with comma */
463 } else /* just a single number */
465 repeat(p, pos, count, count2);
466 if (!EAT('}')) { /* error heuristics */
467 while (MORE() && PEEK() != '}')
469 (void)REQUIRE(MORE(), REG_EBRACE);
478 if (!( c == '*' || c == '+' || c == '?' ||
479 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
481 SETERROR(REG_BADRPT);
485 - p_str - string (no metacharacters) "parser"
486 == static void p_str(struct parse *p);
489 p_str(struct parse *p)
491 (void)REQUIRE(MORE(), REG_EMPTY);
493 ordinary(p, WGETNEXT());
497 - p_bre - BRE parser top level, anchoring and concatenation
498 == static void p_bre(struct parse *p, int end1, \
500 * Giving end1 as OUT essentially eliminates the end1/end2 check.
502 * This implementation is a bit of a kludge, in that a trailing $ is first
503 * taken as an ordinary character and then revised to be an anchor.
504 * The amount of lookahead needed to avoid this kludge is excessive.
507 p_bre(struct parse *p,
508 int end1, /* first terminating character */
509 int end2) /* second terminating character */
511 sopno start = HERE();
512 int first = 1; /* first subexpression? */
517 p->g->iflags |= USEBOL;
520 while (MORE() && !SEETWO(end1, end2)) {
521 wasdollar = p_simp_re(p, first);
524 if (wasdollar) { /* oops, that was a trailing anchor */
527 p->g->iflags |= USEEOL;
531 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
535 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
536 == static int p_simp_re(struct parse *p, int starordinary);
538 static int /* was the simple RE an unbackslashed $? */
539 p_simp_re(struct parse *p,
540 int starordinary) /* is a leading * an ordinary character? */
549 # define BACKSL (1<<CHAR_BIT)
551 pos = HERE(); /* repetion op, if any, covers from here */
553 assert(MORE()); /* caller should have ensured this */
556 (void)REQUIRE(MORE(), REG_EESCAPE);
557 c = BACKSL | GETNEXT();
561 if (p->g->cflags®_NEWLINE)
570 SETERROR(REG_BADRPT);
576 p->pbegin[subno] = HERE();
577 EMIT(OLPAREN, subno);
578 /* the MORE here is an error heuristic */
579 if (MORE() && !SEETWO('\\', ')'))
581 if (subno < NPAREN) {
582 p->pend[subno] = HERE();
583 assert(p->pend[subno] != 0);
585 EMIT(ORPAREN, subno);
586 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
588 case BACKSL|')': /* should not get here -- must be user */
590 SETERROR(REG_EPAREN);
601 i = (c&~BACKSL) - '0';
603 if (p->pend[i] != 0) {
604 assert(i <= p->g->nsub);
606 assert(p->pbegin[i] != 0);
607 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
608 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
609 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
612 SETERROR(REG_ESUBREG);
616 (void)REQUIRE(starordinary, REG_BADRPT);
625 if (EAT('*')) { /* implemented as +? */
626 /* this case does not require the (y|) trick, noKLUDGE */
629 INSERT(OQUEST_, pos);
630 ASTERN(O_QUEST, pos);
631 } else if (EATTWO('\\', '{')) {
634 if (MORE() && isdigit((uch)PEEK())) {
636 (void)REQUIRE(count <= count2, REG_BADBR);
637 } else /* single number with comma */
639 } else /* just a single number */
641 repeat(p, pos, count, count2);
642 if (!EATTWO('\\', '}')) { /* error heuristics */
643 while (MORE() && !SEETWO('\\', '}'))
645 (void)REQUIRE(MORE(), REG_EBRACE);
648 } else if (c == '$') /* $ (but not \$) ends it */
655 - p_count - parse a repetition count
656 == static int p_count(struct parse *p);
658 static int /* the value */
659 p_count(struct parse *p)
664 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
665 count = count*10 + (GETNEXT() - '0');
669 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
674 - p_bracket - parse a bracketed character list
675 == static void p_bracket(struct parse *p);
678 p_bracket(struct parse *p)
683 /* Dept of Truly Sickening Special-Case Kludges */
684 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
689 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
695 if ((cs = allocset(p)) == NULL)
698 if (p->g->cflags®_ICASE)
706 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
710 (void)MUSTEAT(']', REG_EBRACK);
712 if (p->error != 0) /* don't mess things up further */
715 if (cs->invert && p->g->cflags®_NEWLINE)
716 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
718 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
722 EMIT(OANYOF, (int)(cs - p->g->sets));
726 - p_b_term - parse one term of a bracketed character list
727 == static void p_b_term(struct parse *p, cset *cs);
730 p_b_term(struct parse *p, cset *cs)
733 wint_t start, finish;
735 struct xlocale_collate *table =
736 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
738 /* classify what we've got */
739 switch ((MORE()) ? PEEK() : '\0') {
741 c = (MORE2()) ? PEEK2() : '\0';
744 SETERROR(REG_ERANGE);
745 return; /* NOTE RETURN */
753 case ':': /* character class */
755 (void)REQUIRE(MORE(), REG_EBRACK);
757 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
759 (void)REQUIRE(MORE(), REG_EBRACK);
760 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
762 case '=': /* equivalence class */
764 (void)REQUIRE(MORE(), REG_EBRACK);
766 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
768 (void)REQUIRE(MORE(), REG_EBRACK);
769 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
771 default: /* symbol, ordinary character, or range */
772 start = p_b_symbol(p);
773 if (SEE('-') && MORE2() && PEEK2() != ']') {
779 finish = p_b_symbol(p);
785 if (table->__collate_load_error) {
786 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
787 CHaddrange(p, cs, start, finish);
789 (void)REQUIRE(__collate_range_cmp(table, start, finish) <= 0, REG_ERANGE);
790 for (i = 0; i <= UCHAR_MAX; i++) {
791 if ( __collate_range_cmp(table, start, i) <= 0
792 && __collate_range_cmp(table, i, finish) <= 0
803 - p_b_cclass - parse a character-class name and deal with it
804 == static void p_b_cclass(struct parse *p, cset *cs);
807 p_b_cclass(struct parse *p, cset *cs)
814 while (MORE() && isalpha((uch)PEEK()))
817 if (len >= sizeof(clname) - 1) {
818 SETERROR(REG_ECTYPE);
821 memcpy(clname, sp, len);
823 if ((wct = wctype(clname)) == 0) {
824 SETERROR(REG_ECTYPE);
827 CHaddtype(p, cs, wct);
831 - p_b_eclass - parse an equivalence-class name and deal with it
832 == static void p_b_eclass(struct parse *p, cset *cs);
834 * This implementation is incomplete. xxx
837 p_b_eclass(struct parse *p, cset *cs)
841 c = p_b_coll_elem(p, '=');
846 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
847 == static wint_t p_b_symbol(struct parse *p);
849 static wint_t /* value of symbol */
850 p_b_symbol(struct parse *p)
854 (void)REQUIRE(MORE(), REG_EBRACK);
855 if (!EATTWO('[', '.'))
858 /* collating symbol */
859 value = p_b_coll_elem(p, '.');
860 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
865 - p_b_coll_elem - parse a collating-element name and look it up
866 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
868 static wint_t /* value of collating element */
869 p_b_coll_elem(struct parse *p,
870 wint_t endc) /* name ended by endc,']' */
879 while (MORE() && !SEETWO(endc, ']'))
882 SETERROR(REG_EBRACK);
886 for (cp = cnames; cp->name != NULL; cp++)
887 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
888 return(cp->code); /* known name */
889 memset(&mbs, 0, sizeof(mbs));
890 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
891 return (wc); /* single character */
892 else if (clen == (size_t)-1 || clen == (size_t)-2)
893 SETERROR(REG_ILLSEQ);
895 SETERROR(REG_ECOLLATE); /* neither */
900 - othercase - return the case counterpart of an alphabetic
901 == static wint_t othercase(wint_t ch);
903 static wint_t /* if no counterpart, return ch */
906 assert(iswalpha(ch));
908 return(towlower(ch));
909 else if (iswlower(ch))
910 return(towupper(ch));
911 else /* peculiar, but could happen */
916 - bothcases - emit a dualcase version of a two-case character
917 == static void bothcases(struct parse *p, wint_t ch);
919 * Boy, is this implementation ever a kludge...
922 bothcases(struct parse *p, wint_t ch)
924 char *oldnext = p->next;
925 char *oldend = p->end;
926 char bracket[3 + MB_LEN_MAX];
930 assert(othercase(ch) != ch); /* p_bracket() would recurse */
932 memset(&mbs, 0, sizeof(mbs));
933 n = wcrtomb(bracket, ch, &mbs);
934 assert(n != (size_t)-1);
936 bracket[n + 1] = '\0';
937 p->end = bracket+n+1;
939 assert(p->next == p->end);
945 - ordinary - emit an ordinary character
946 == static void ordinary(struct parse *p, wint_t ch);
949 ordinary(struct parse *p, wint_t ch)
953 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
955 else if ((ch & OPDMASK) == ch)
959 * Kludge: character is too big to fit into an OCHAR operand.
960 * Emit a singleton set.
962 if ((cs = allocset(p)) == NULL)
965 EMIT(OANYOF, (int)(cs - p->g->sets));
970 - nonnewline - emit REG_NEWLINE version of OANY
971 == static void nonnewline(struct parse *p);
973 * Boy, is this implementation ever a kludge...
976 nonnewline(struct parse *p)
978 char *oldnext = p->next;
979 char *oldend = p->end;
989 assert(p->next == bracket+3);
995 - repeat - generate code for a bounded repetition, recursively if needed
996 == static void repeat(struct parse *p, sopno start, int from, int to);
999 repeat(struct parse *p,
1000 sopno start, /* operand from here to end of strip */
1001 int from, /* repeated from this number */
1002 int to) /* to this number of times (maybe INFINITY) */
1004 sopno finish = HERE();
1007 # define REP(f, t) ((f)*8 + (t))
1008 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1011 if (p->error != 0) /* head off possible runaway recursion */
1016 switch (REP(MAP(from), MAP(to))) {
1017 case REP(0, 0): /* must be user doing this */
1018 DROP(finish-start); /* drop the operand */
1020 case REP(0, 1): /* as x{1,1}? */
1021 case REP(0, N): /* as x{1,n}? */
1022 case REP(0, INF): /* as x{1,}? */
1023 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1024 INSERT(OCH_, start); /* offset is wrong... */
1025 repeat(p, start+1, 1, to);
1026 ASTERN(OOR1, start);
1027 AHEAD(start); /* ... fix it */
1030 ASTERN(O_CH, THERETHERE());
1032 case REP(1, 1): /* trivial case */
1035 case REP(1, N): /* as x?x{1,n-1} */
1036 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1037 INSERT(OCH_, start);
1038 ASTERN(OOR1, start);
1040 EMIT(OOR2, 0); /* offset very wrong... */
1041 AHEAD(THERE()); /* ...so fix it */
1042 ASTERN(O_CH, THERETHERE());
1043 copy = dupl(p, start+1, finish+1);
1044 assert(copy == finish+4);
1045 repeat(p, copy, 1, to-1);
1047 case REP(1, INF): /* as x+ */
1048 INSERT(OPLUS_, start);
1049 ASTERN(O_PLUS, start);
1051 case REP(N, N): /* as xx{m-1,n-1} */
1052 copy = dupl(p, start, finish);
1053 repeat(p, copy, from-1, to-1);
1055 case REP(N, INF): /* as xx{n-1,INF} */
1056 copy = dupl(p, start, finish);
1057 repeat(p, copy, from-1, to);
1059 default: /* "can't happen" */
1060 SETERROR(REG_ASSERT); /* just in case */
1066 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1067 - character from the parse struct, signals a REG_ILLSEQ error if the
1068 - character can't be converted. Returns the number of bytes consumed.
1071 wgetnext(struct parse *p)
1077 memset(&mbs, 0, sizeof(mbs));
1078 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1079 if (n == (size_t)-1 || n == (size_t)-2) {
1080 SETERROR(REG_ILLSEQ);
1090 - seterr - set an error condition
1091 == static int seterr(struct parse *p, int e);
1093 static int /* useless but makes type checking happy */
1094 seterr(struct parse *p, int e)
1096 if (p->error == 0) /* keep earliest error condition */
1098 p->next = nuls; /* try to bring things to a halt */
1100 return(0); /* make the return value well-defined */
1104 - allocset - allocate a set of characters for []
1105 == static cset *allocset(struct parse *p);
1108 allocset(struct parse *p)
1112 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1114 SETERROR(REG_ESPACE);
1118 cs = &p->g->sets[p->g->ncsets++];
1119 memset(cs, 0, sizeof(*cs));
1125 - freeset - free a now-unused set
1126 == static void freeset(struct parse *p, cset *cs);
1129 freeset(struct parse *p, cset *cs)
1131 cset *top = &p->g->sets[p->g->ncsets];
1136 memset(cs, 0, sizeof(*cs));
1137 if (cs == top-1) /* recover only the easy case */
1142 - singleton - Determine whether a set contains only one character,
1143 - returning it if so, otherwise returning OUT.
1150 for (i = n = 0; i < NC; i++)
1157 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1159 return (cs->wides[0]);
1160 /* Don't bother handling the other cases. */
1165 - CHadd - add character to character set.
1168 CHadd(struct parse *p, cset *cs, wint_t ch)
1170 wint_t nch, *newwides;
1173 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1175 newwides = realloc(cs->wides, (cs->nwides + 1) *
1176 sizeof(*cs->wides));
1177 if (newwides == NULL) {
1178 SETERROR(REG_ESPACE);
1181 cs->wides = newwides;
1182 cs->wides[cs->nwides++] = ch;
1185 if ((nch = towlower(ch)) < NC)
1186 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1187 if ((nch = towupper(ch)) < NC)
1188 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1193 - CHaddrange - add all characters in the range [min,max] to a character set.
1196 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1200 for (; min < NC && min <= max; min++)
1204 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1205 sizeof(*cs->ranges));
1206 if (newranges == NULL) {
1207 SETERROR(REG_ESPACE);
1210 cs->ranges = newranges;
1211 cs->ranges[cs->nranges].min = min;
1212 cs->ranges[cs->nranges].max = max;
1217 - CHaddtype - add all characters of a certain type to a character set.
1220 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1225 for (i = 0; i < NC; i++)
1226 if (iswctype(i, wct))
1228 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1229 sizeof(*cs->types));
1230 if (newtypes == NULL) {
1231 SETERROR(REG_ESPACE);
1234 cs->types = newtypes;
1235 cs->types[cs->ntypes++] = wct;
1239 - dupl - emit a duplicate of a bunch of sops
1240 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1242 static sopno /* start of duplicate */
1243 dupl(struct parse *p,
1244 sopno start, /* from here */
1245 sopno finish) /* to this less one */
1248 sopno len = finish - start;
1250 assert(finish >= start);
1253 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1255 (void) memcpy((char *)(p->strip + p->slen),
1256 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1262 - doemit - emit a strip operator
1263 == static void doemit(struct parse *p, sop op, size_t opnd);
1265 * It might seem better to implement this as a macro with a function as
1266 * hard-case backup, but it's just too big and messy unless there are
1267 * some changes to the data structures. Maybe later.
1270 doemit(struct parse *p, sop op, size_t opnd)
1272 /* avoid making error situations worse */
1276 /* deal with oversize operands ("can't happen", more or less) */
1277 assert(opnd < 1<<OPSHIFT);
1279 /* deal with undersized strip */
1280 if (p->slen >= p->ssize)
1281 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1284 /* finally, it's all reduced to the easy case */
1285 p->strip[p->slen++] = SOP(op, opnd);
1289 - doinsert - insert a sop into the strip
1290 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1293 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1299 /* avoid making error situations worse */
1304 EMIT(op, opnd); /* do checks, ensure space */
1305 assert(HERE() == sn+1);
1308 /* adjust paren pointers */
1310 for (i = 1; i < NPAREN; i++) {
1311 if (p->pbegin[i] >= pos) {
1314 if (p->pend[i] >= pos) {
1319 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1320 (HERE()-pos-1)*sizeof(sop));
1325 - dofwd - complete a forward reference
1326 == static void dofwd(struct parse *p, sopno pos, sop value);
1329 dofwd(struct parse *p, sopno pos, sop value)
1331 /* avoid making error situations worse */
1335 assert(value < 1<<OPSHIFT);
1336 p->strip[pos] = OP(p->strip[pos]) | value;
1340 - enlarge - enlarge the strip
1341 == static int enlarge(struct parse *p, sopno size);
1344 enlarge(struct parse *p, sopno size)
1348 if (p->ssize >= size)
1351 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1353 SETERROR(REG_ESPACE);
1362 - stripsnug - compact the strip
1363 == static void stripsnug(struct parse *p, struct re_guts *g);
1366 stripsnug(struct parse *p, struct re_guts *g)
1368 g->nstates = p->slen;
1369 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1370 if (g->strip == NULL) {
1371 SETERROR(REG_ESPACE);
1372 g->strip = p->strip;
1377 - findmust - fill in must and mlen with longest mandatory literal string
1378 == static void findmust(struct parse *p, struct re_guts *g);
1380 * This algorithm could do fancy things like analyzing the operands of |
1381 * for common subsequences. Someday. This code is simple and finds most
1382 * of the interesting cases.
1384 * Note that must and mlen got initialized during setup.
1387 findmust(struct parse *p, struct re_guts *g)
1396 char buf[MB_LEN_MAX];
1400 /* avoid making error situations worse */
1405 * It's not generally safe to do a ``char'' substring search on
1406 * multibyte character strings, but it's safe for at least
1407 * UTF-8 (see RFC 3629).
1409 if (MB_CUR_MAX > 1 &&
1410 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1413 /* find the longest OCHAR sequence in strip */
1417 scan = g->strip + 1;
1421 case OCHAR: /* sequence member */
1422 if (newlen == 0) { /* new sequence */
1423 memset(&mbs, 0, sizeof(mbs));
1424 newstart = scan - 1;
1426 clen = wcrtomb(buf, OPND(s), &mbs);
1427 if (clen == (size_t)-1)
1431 case OPLUS_: /* things that don't break one */
1435 case OQUEST_: /* things that must be skipped */
1437 offset = altoffset(scan, offset);
1442 /* assert() interferes w debug printouts */
1443 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1448 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1450 case OBOW: /* things that break a sequence */
1457 if (newlen > g->mlen) { /* ends one */
1461 g->moffset += offset;
1464 g->moffset = offset;
1472 if (newlen > g->mlen) { /* ends one */
1476 g->moffset += offset;
1479 g->moffset = offset;
1488 case OANYOF: /* may or may not invalidate offset */
1489 /* First, everything as OANY */
1490 if (newlen > g->mlen) { /* ends one */
1494 g->moffset += offset;
1497 g->moffset = offset;
1508 /* Anything here makes it impossible or too hard
1509 * to calculate the offset -- so we give up;
1510 * save the last known good offset, in case the
1511 * must sequence doesn't occur later.
1513 if (newlen > g->mlen) { /* ends one */
1517 g->moffset += offset;
1519 g->moffset = offset;
1525 } while (OP(s) != OEND);
1527 if (g->mlen == 0) { /* there isn't one */
1532 /* turn it into a character string */
1533 g->must = malloc((size_t)g->mlen + 1);
1534 if (g->must == NULL) { /* argh; just forget it */
1541 memset(&mbs, 0, sizeof(mbs));
1542 while (cp < g->must + g->mlen) {
1543 while (OP(s = *scan++) != OCHAR)
1545 clen = wcrtomb(cp, OPND(s), &mbs);
1546 assert(clen != (size_t)-1);
1549 assert(cp == g->must + g->mlen);
1550 *cp++ = '\0'; /* just on general principles */
1554 - altoffset - choose biggest offset among multiple choices
1555 == static int altoffset(sop *scan, int offset);
1557 * Compute, recursively if necessary, the largest offset among multiple
1561 altoffset(sop *scan, int offset)
1567 /* If we gave up already on offsets, return */
1574 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1583 try = altoffset(scan, try);
1590 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1593 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1594 /* We must skip to the next position, or we'll
1595 * leave altoffset() too early.
1621 return largest+offset;
1625 - computejumps - compute char jumps for BM scan
1626 == static void computejumps(struct parse *p, struct re_guts *g);
1628 * This algorithm assumes g->must exists and is has size greater than
1629 * zero. It's based on the algorithm found on Computer Algorithms by
1632 * A char jump is the number of characters one needs to jump based on
1633 * the value of the character from the text that was mismatched.
1636 computejumps(struct parse *p, struct re_guts *g)
1641 /* Avoid making errors worse */
1645 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1646 if (g->charjump == NULL) /* Not a fatal error */
1648 /* Adjust for signed chars, if necessary */
1649 g->charjump = &g->charjump[-(CHAR_MIN)];
1651 /* If the character does not exist in the pattern, the jump
1652 * is equal to the number of characters in the pattern.
1654 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1655 g->charjump[ch] = g->mlen;
1657 /* If the character does exist, compute the jump that would
1658 * take us to the last character in the pattern equal to it
1659 * (notice that we match right to left, so that last character
1660 * is the first one that would be matched).
1662 for (mindex = 0; mindex < g->mlen; mindex++)
1663 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1667 - computematchjumps - compute match jumps for BM scan
1668 == static void computematchjumps(struct parse *p, struct re_guts *g);
1670 * This algorithm assumes g->must exists and is has size greater than
1671 * zero. It's based on the algorithm found on Computer Algorithms by
1674 * A match jump is the number of characters one needs to advance based
1675 * on the already-matched suffix.
1676 * Notice that all values here are minus (g->mlen-1), because of the way
1677 * the search algorithm works.
1680 computematchjumps(struct parse *p, struct re_guts *g)
1682 int mindex; /* General "must" iterator */
1683 int suffix; /* Keeps track of matching suffix */
1684 int ssuffix; /* Keeps track of suffixes' suffix */
1685 int* pmatches; /* pmatches[k] points to the next i
1686 * such that i+1...mlen is a substring
1687 * of k+1...k+mlen-i-1
1690 /* Avoid making errors worse */
1694 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1695 if (pmatches == NULL) {
1696 g->matchjump = NULL;
1700 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1701 if (g->matchjump == NULL) /* Not a fatal error */
1704 /* Set maximum possible jump for each character in the pattern */
1705 for (mindex = 0; mindex < g->mlen; mindex++)
1706 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1708 /* Compute pmatches[] */
1709 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1710 mindex--, suffix--) {
1711 pmatches[mindex] = suffix;
1713 /* If a mismatch is found, interrupting the substring,
1714 * compute the matchjump for that position. If no
1715 * mismatch is found, then a text substring mismatched
1716 * against the suffix will also mismatch against the
1719 while (suffix < g->mlen
1720 && g->must[mindex] != g->must[suffix]) {
1721 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1722 g->mlen - mindex - 1);
1723 suffix = pmatches[suffix];
1727 /* Compute the matchjump up to the last substring found to jump
1728 * to the beginning of the largest must pattern prefix matching
1731 for (mindex = 0; mindex <= suffix; mindex++)
1732 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1733 g->mlen + suffix - mindex);
1735 ssuffix = pmatches[suffix];
1736 while (suffix < g->mlen) {
1737 while (suffix <= ssuffix && suffix < g->mlen) {
1738 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1739 g->mlen + ssuffix - suffix);
1742 if (suffix < g->mlen)
1743 ssuffix = pmatches[ssuffix];
1750 - pluscount - count + nesting
1751 == static sopno pluscount(struct parse *p, struct re_guts *g);
1753 static sopno /* nesting depth */
1754 pluscount(struct parse *p, struct re_guts *g)
1762 return(0); /* there may not be an OEND */
1764 scan = g->strip + 1;
1772 if (plusnest > maxnest)
1777 } while (OP(s) != OEND);