2 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
36 #if defined(LIBC_SCCS) && !defined(lint)
37 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
38 #endif /* LIBC_SCCS and not lint */
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include <sys/types.h>
61 * parse structure, passed up and down to avoid global variables and
65 char *next; /* next character in RE */
66 char *end; /* end of string (-> NUL normally) */
67 int error; /* has an error been seen? */
68 sop *strip; /* malloced strip */
69 sopno ssize; /* malloced strip size (allocated) */
70 sopno slen; /* malloced strip length (used) */
71 int ncsalloc; /* number of csets allocated */
73 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
74 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
75 sopno pend[NPAREN]; /* -> ) ([0] unused) */
78 /* ========= begin header generated by ./mkh ========= */
83 /* === regcomp.c === */
84 static void p_ere(struct parse *p, wint_t stop);
85 static void p_ere_exp(struct parse *p);
86 static void p_str(struct parse *p);
87 static void p_bre(struct parse *p, wint_t end1, wint_t end2);
88 static int p_simp_re(struct parse *p, int starordinary);
89 static int p_count(struct parse *p);
90 static void p_bracket(struct parse *p);
91 static void p_b_term(struct parse *p, cset *cs);
92 static void p_b_cclass(struct parse *p, cset *cs);
93 static void p_b_eclass(struct parse *p, cset *cs);
94 static wint_t p_b_symbol(struct parse *p);
95 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
96 static wint_t othercase(wint_t ch);
97 static void bothcases(struct parse *p, wint_t ch);
98 static void ordinary(struct parse *p, wint_t ch);
99 static void nonnewline(struct parse *p);
100 static void repeat(struct parse *p, sopno start, int from, int to);
101 static int seterr(struct parse *p, int e);
102 static cset *allocset(struct parse *p);
103 static void freeset(struct parse *p, cset *cs);
104 static void CHadd(struct parse *p, cset *cs, wint_t ch);
105 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
106 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
107 static wint_t singleton(cset *cs);
108 static sopno dupl(struct parse *p, sopno start, sopno finish);
109 static void doemit(struct parse *p, sop op, size_t opnd);
110 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
111 static void dofwd(struct parse *p, sopno pos, sop value);
112 static void enlarge(struct parse *p, sopno size);
113 static void stripsnug(struct parse *p, struct re_guts *g);
114 static void findmust(struct parse *p, struct re_guts *g);
115 static int altoffset(sop *scan, int offset);
116 static void computejumps(struct parse *p, struct re_guts *g);
117 static void computematchjumps(struct parse *p, struct re_guts *g);
118 static sopno pluscount(struct parse *p, struct re_guts *g);
119 static wint_t wgetnext(struct parse *p);
124 /* ========= end header generated by ./mkh ========= */
126 static char nuls[10]; /* place to point scanner in event of error */
129 * macros for use with parse structure
130 * BEWARE: these know that the parse structure is named `p' !!!
132 #define PEEK() (*p->next)
133 #define PEEK2() (*(p->next+1))
134 #define MORE() (p->next < p->end)
135 #define MORE2() (p->next+1 < p->end)
136 #define SEE(c) (MORE() && PEEK() == (c))
137 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
138 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
139 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
140 #define NEXT() (p->next++)
141 #define NEXT2() (p->next += 2)
142 #define NEXTn(n) (p->next += (n))
143 #define GETNEXT() (*p->next++)
144 #define WGETNEXT() wgetnext(p)
145 #define SETERROR(e) seterr(p, (e))
146 #define REQUIRE(co, e) ((co) || SETERROR(e))
147 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
148 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
149 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
150 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
151 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
152 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
153 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
154 #define HERE() (p->slen)
155 #define THERE() (p->slen - 1)
156 #define THERETHERE() (p->slen - 2)
157 #define DROP(n) (p->slen -= (n))
160 static int never = 0; /* for use in asserts; shuts lint up */
162 #define never 0 /* some <assert.h>s have bugs too */
165 /* Macro used by computejump()/computematchjump() */
166 #define MIN(a,b) ((a)<(b)?(a):(b))
169 - regcomp - interface for parser and compilation
170 = extern int regcomp(regex_t *, const char *, int);
171 = #define REG_BASIC 0000
172 = #define REG_EXTENDED 0001
173 = #define REG_ICASE 0002
174 = #define REG_NOSUB 0004
175 = #define REG_NEWLINE 0010
176 = #define REG_NOSPEC 0020
177 = #define REG_PEND 0040
178 = #define REG_DUMP 0200
180 int /* 0 success, otherwise REG_something */
181 regcomp(regex_t * __restrict preg,
182 const char * __restrict pattern,
187 struct parse *p = &pa;
191 # define GOODFLAGS(f) (f)
193 # define GOODFLAGS(f) ((f)&~REG_DUMP)
196 cflags = GOODFLAGS(cflags);
197 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
200 if (cflags®_PEND) {
201 if (preg->re_endp < pattern)
203 len = preg->re_endp - pattern;
205 len = strlen((char *)pattern);
207 /* do the mallocs early so failure handling is easy */
208 g = (struct re_guts *)malloc(sizeof(struct re_guts));
211 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
212 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
214 if (p->strip == NULL) {
221 p->next = (char *)pattern; /* convenience; we do not modify it */
222 p->end = p->next + len;
225 for (i = 0; i < NPAREN; i++) {
245 g->firststate = THERE();
246 if (cflags®_EXTENDED)
248 else if (cflags®_NOSPEC)
253 g->laststate = THERE();
255 /* tidy up loose ends and fill things in */
258 /* only use Boyer-Moore algorithm if the pattern is bigger
259 * than three characters
263 computematchjumps(p, g);
264 if(g->matchjump == NULL && g->charjump != NULL) {
269 g->nplus = pluscount(p, g);
271 preg->re_nsub = g->nsub;
273 preg->re_magic = MAGIC1;
275 /* not debugging, so can't rely on the assert() in regexec() */
277 SETERROR(REG_ASSERT);
280 /* win or lose, we're done */
281 if (p->error != 0) /* lose */
287 - p_ere - ERE parser top level, concatenation and alternation
288 == static void p_ere(struct parse *p, int stop);
291 p_ere(struct parse *p,
292 int stop) /* character this ERE should end at */
298 int first = 1; /* is this the first alternative? */
301 /* do a bunch of concatenated expressions */
303 while (MORE() && (c = PEEK()) != '|' && c != stop)
305 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
308 break; /* NOTE BREAK OUT */
311 INSERT(OCH_, conc); /* offset is wrong */
316 ASTERN(OOR1, prevback);
318 AHEAD(prevfwd); /* fix previous offset */
320 EMIT(OOR2, 0); /* offset is very wrong */
323 if (!first) { /* tail-end fixups */
325 ASTERN(O_CH, prevback);
328 assert(!MORE() || SEE(stop));
332 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
333 == static void p_ere_exp(struct parse *p);
336 p_ere_exp(struct parse *p)
346 assert(MORE()); /* caller should have ensured this */
352 (void)REQUIRE(MORE(), REG_EPAREN);
356 p->pbegin[subno] = HERE();
357 EMIT(OLPAREN, subno);
360 if (subno < NPAREN) {
361 p->pend[subno] = HERE();
362 assert(p->pend[subno] != 0);
364 EMIT(ORPAREN, subno);
365 (void)MUSTEAT(')', REG_EPAREN);
367 #ifndef POSIX_MISTAKE
368 case ')': /* happens only if no current unmatched ( */
370 * You may ask, why the ifndef? Because I didn't notice
371 * this until slightly too late for 1003.2, and none of the
372 * other 1003.2 regular-expression reviewers noticed it at
373 * all. So an unmatched ) is legal POSIX, at least until
374 * we can get it fixed.
376 SETERROR(REG_EPAREN);
381 p->g->iflags |= USEBOL;
387 p->g->iflags |= USEEOL;
396 SETERROR(REG_BADRPT);
399 if (p->g->cflags®_NEWLINE)
408 (void)REQUIRE(MORE(), REG_EESCAPE);
412 case '{': /* okay as ordinary except if digit follows */
413 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
425 /* we call { a repetition if followed by a digit */
426 if (!( c == '*' || c == '+' || c == '?' ||
427 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
428 return; /* no repetition, we're done */
431 (void)REQUIRE(!wascaret, REG_BADRPT);
433 case '*': /* implemented as +? */
434 /* this case does not require the (y|) trick, noKLUDGE */
437 INSERT(OQUEST_, pos);
438 ASTERN(O_QUEST, pos);
445 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
446 INSERT(OCH_, pos); /* offset slightly wrong */
447 ASTERN(OOR1, pos); /* this one's right */
448 AHEAD(pos); /* fix the OCH_ */
449 EMIT(OOR2, 0); /* offset very wrong... */
450 AHEAD(THERE()); /* ...so fix it */
451 ASTERN(O_CH, THERETHERE());
456 if (isdigit((uch)PEEK())) {
458 (void)REQUIRE(count <= count2, REG_BADBR);
459 } else /* single number with comma */
461 } else /* just a single number */
463 repeat(p, pos, count, count2);
464 if (!EAT('}')) { /* error heuristics */
465 while (MORE() && PEEK() != '}')
467 (void)REQUIRE(MORE(), REG_EBRACE);
476 if (!( c == '*' || c == '+' || c == '?' ||
477 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
479 SETERROR(REG_BADRPT);
483 - p_str - string (no metacharacters) "parser"
484 == static void p_str(struct parse *p);
487 p_str(struct parse *p)
489 (void)REQUIRE(MORE(), REG_EMPTY);
491 ordinary(p, WGETNEXT());
495 - p_bre - BRE parser top level, anchoring and concatenation
496 == static void p_bre(struct parse *p, int end1, \
498 * Giving end1 as OUT essentially eliminates the end1/end2 check.
500 * This implementation is a bit of a kludge, in that a trailing $ is first
501 * taken as an ordinary character and then revised to be an anchor.
502 * The amount of lookahead needed to avoid this kludge is excessive.
505 p_bre(struct parse *p,
506 int end1, /* first terminating character */
507 int end2) /* second terminating character */
509 sopno start = HERE();
510 int first = 1; /* first subexpression? */
515 p->g->iflags |= USEBOL;
518 while (MORE() && !SEETWO(end1, end2)) {
519 wasdollar = p_simp_re(p, first);
522 if (wasdollar) { /* oops, that was a trailing anchor */
525 p->g->iflags |= USEEOL;
529 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
533 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
534 == static int p_simp_re(struct parse *p, int starordinary);
536 static int /* was the simple RE an unbackslashed $? */
537 p_simp_re(struct parse *p,
538 int starordinary) /* is a leading * an ordinary character? */
547 # define BACKSL (1<<CHAR_BIT)
549 pos = HERE(); /* repetion op, if any, covers from here */
551 assert(MORE()); /* caller should have ensured this */
554 (void)REQUIRE(MORE(), REG_EESCAPE);
555 c = BACKSL | GETNEXT();
559 if (p->g->cflags®_NEWLINE)
568 SETERROR(REG_BADRPT);
574 p->pbegin[subno] = HERE();
575 EMIT(OLPAREN, subno);
576 /* the MORE here is an error heuristic */
577 if (MORE() && !SEETWO('\\', ')'))
579 if (subno < NPAREN) {
580 p->pend[subno] = HERE();
581 assert(p->pend[subno] != 0);
583 EMIT(ORPAREN, subno);
584 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
586 case BACKSL|')': /* should not get here -- must be user */
588 SETERROR(REG_EPAREN);
599 i = (c&~BACKSL) - '0';
601 if (p->pend[i] != 0) {
602 assert(i <= p->g->nsub);
604 assert(p->pbegin[i] != 0);
605 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
606 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
607 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
610 SETERROR(REG_ESUBREG);
614 (void)REQUIRE(starordinary, REG_BADRPT);
623 if (EAT('*')) { /* implemented as +? */
624 /* this case does not require the (y|) trick, noKLUDGE */
627 INSERT(OQUEST_, pos);
628 ASTERN(O_QUEST, pos);
629 } else if (EATTWO('\\', '{')) {
632 if (MORE() && isdigit((uch)PEEK())) {
634 (void)REQUIRE(count <= count2, REG_BADBR);
635 } else /* single number with comma */
637 } else /* just a single number */
639 repeat(p, pos, count, count2);
640 if (!EATTWO('\\', '}')) { /* error heuristics */
641 while (MORE() && !SEETWO('\\', '}'))
643 (void)REQUIRE(MORE(), REG_EBRACE);
646 } else if (c == '$') /* $ (but not \$) ends it */
653 - p_count - parse a repetition count
654 == static int p_count(struct parse *p);
656 static int /* the value */
657 p_count(struct parse *p)
662 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
663 count = count*10 + (GETNEXT() - '0');
667 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
672 - p_bracket - parse a bracketed character list
673 == static void p_bracket(struct parse *p);
676 p_bracket(struct parse *p)
681 /* Dept of Truly Sickening Special-Case Kludges */
682 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
687 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
693 if ((cs = allocset(p)) == NULL)
696 if (p->g->cflags®_ICASE)
704 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
708 (void)MUSTEAT(']', REG_EBRACK);
710 if (p->error != 0) /* don't mess things up further */
713 if (cs->invert && p->g->cflags®_NEWLINE)
714 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
716 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
720 EMIT(OANYOF, (int)(cs - p->g->sets));
724 - p_b_term - parse one term of a bracketed character list
725 == static void p_b_term(struct parse *p, cset *cs);
728 p_b_term(struct parse *p, cset *cs)
731 wint_t start, finish;
734 /* classify what we've got */
735 switch ((MORE()) ? PEEK() : '\0') {
737 c = (MORE2()) ? PEEK2() : '\0';
740 SETERROR(REG_ERANGE);
741 return; /* NOTE RETURN */
749 case ':': /* character class */
751 (void)REQUIRE(MORE(), REG_EBRACK);
753 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
755 (void)REQUIRE(MORE(), REG_EBRACK);
756 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
758 case '=': /* equivalence class */
760 (void)REQUIRE(MORE(), REG_EBRACK);
762 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
764 (void)REQUIRE(MORE(), REG_EBRACK);
765 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
767 default: /* symbol, ordinary character, or range */
768 start = p_b_symbol(p);
769 if (SEE('-') && MORE2() && PEEK2() != ']') {
775 finish = p_b_symbol(p);
781 if (__collate_load_error) {
782 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
783 CHaddrange(p, cs, start, finish);
785 (void)REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE);
786 for (i = 0; i <= UCHAR_MAX; i++) {
787 if ( __collate_range_cmp(start, i) <= 0
788 && __collate_range_cmp(i, finish) <= 0
799 - p_b_cclass - parse a character-class name and deal with it
800 == static void p_b_cclass(struct parse *p, cset *cs);
803 p_b_cclass(struct parse *p, cset *cs)
810 while (MORE() && isalpha((uch)PEEK()))
813 if (len >= sizeof(clname) - 1) {
814 SETERROR(REG_ECTYPE);
817 memcpy(clname, sp, len);
819 if ((wct = wctype(clname)) == 0) {
820 SETERROR(REG_ECTYPE);
823 CHaddtype(p, cs, wct);
827 - p_b_eclass - parse an equivalence-class name and deal with it
828 == static void p_b_eclass(struct parse *p, cset *cs);
830 * This implementation is incomplete. xxx
833 p_b_eclass(struct parse *p, cset *cs)
837 c = p_b_coll_elem(p, '=');
842 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
843 == static char p_b_symbol(struct parse *p);
845 static wint_t /* value of symbol */
846 p_b_symbol(struct parse *p)
850 (void)REQUIRE(MORE(), REG_EBRACK);
851 if (!EATTWO('[', '.'))
854 /* collating symbol */
855 value = p_b_coll_elem(p, '.');
856 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
861 - p_b_coll_elem - parse a collating-element name and look it up
862 == static char p_b_coll_elem(struct parse *p, int endc);
864 static wint_t /* value of collating element */
865 p_b_coll_elem(struct parse *p,
866 wint_t endc) /* name ended by endc,']' */
875 while (MORE() && !SEETWO(endc, ']'))
878 SETERROR(REG_EBRACK);
882 for (cp = cnames; cp->name != NULL; cp++)
883 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
884 return(cp->code); /* known name */
885 memset(&mbs, 0, sizeof(mbs));
886 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
887 return (wc); /* single character */
888 else if (clen == (size_t)-1 || clen == (size_t)-2)
889 SETERROR(REG_ILLSEQ);
891 SETERROR(REG_ECOLLATE); /* neither */
896 - othercase - return the case counterpart of an alphabetic
897 == static char othercase(int ch);
899 static wint_t /* if no counterpart, return ch */
902 assert(iswalpha(ch));
904 return(towlower(ch));
905 else if (iswlower(ch))
906 return(towupper(ch));
907 else /* peculiar, but could happen */
912 - bothcases - emit a dualcase version of a two-case character
913 == static void bothcases(struct parse *p, int ch);
915 * Boy, is this implementation ever a kludge...
918 bothcases(struct parse *p, wint_t ch)
920 char *oldnext = p->next;
921 char *oldend = p->end;
922 char bracket[3 + MB_LEN_MAX];
926 assert(othercase(ch) != ch); /* p_bracket() would recurse */
928 memset(&mbs, 0, sizeof(mbs));
929 n = wcrtomb(bracket, ch, &mbs);
930 assert(n != (size_t)-1);
932 bracket[n + 1] = '\0';
933 p->end = bracket+n+1;
935 assert(p->next == p->end);
941 - ordinary - emit an ordinary character
942 == static void ordinary(struct parse *p, int ch);
945 ordinary(struct parse *p, wint_t ch)
949 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
951 else if ((ch & OPDMASK) == ch)
955 * Kludge: character is too big to fit into an OCHAR operand.
956 * Emit a singleton set.
958 if ((cs = allocset(p)) == NULL)
961 EMIT(OANYOF, (int)(cs - p->g->sets));
966 - nonnewline - emit REG_NEWLINE version of OANY
967 == static void nonnewline(struct parse *p);
969 * Boy, is this implementation ever a kludge...
972 nonnewline(struct parse *p)
974 char *oldnext = p->next;
975 char *oldend = p->end;
985 assert(p->next == bracket+3);
991 - repeat - generate code for a bounded repetition, recursively if needed
992 == static void repeat(struct parse *p, sopno start, int from, int to);
995 repeat(struct parse *p,
996 sopno start, /* operand from here to end of strip */
997 int from, /* repeated from this number */
998 int to) /* to this number of times (maybe INFINITY) */
1000 sopno finish = HERE();
1003 # define REP(f, t) ((f)*8 + (t))
1004 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1007 if (p->error != 0) /* head off possible runaway recursion */
1012 switch (REP(MAP(from), MAP(to))) {
1013 case REP(0, 0): /* must be user doing this */
1014 DROP(finish-start); /* drop the operand */
1016 case REP(0, 1): /* as x{1,1}? */
1017 case REP(0, N): /* as x{1,n}? */
1018 case REP(0, INF): /* as x{1,}? */
1019 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1020 INSERT(OCH_, start); /* offset is wrong... */
1021 repeat(p, start+1, 1, to);
1022 ASTERN(OOR1, start);
1023 AHEAD(start); /* ... fix it */
1026 ASTERN(O_CH, THERETHERE());
1028 case REP(1, 1): /* trivial case */
1031 case REP(1, N): /* as x?x{1,n-1} */
1032 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1033 INSERT(OCH_, start);
1034 ASTERN(OOR1, start);
1036 EMIT(OOR2, 0); /* offset very wrong... */
1037 AHEAD(THERE()); /* ...so fix it */
1038 ASTERN(O_CH, THERETHERE());
1039 copy = dupl(p, start+1, finish+1);
1040 assert(copy == finish+4);
1041 repeat(p, copy, 1, to-1);
1043 case REP(1, INF): /* as x+ */
1044 INSERT(OPLUS_, start);
1045 ASTERN(O_PLUS, start);
1047 case REP(N, N): /* as xx{m-1,n-1} */
1048 copy = dupl(p, start, finish);
1049 repeat(p, copy, from-1, to-1);
1051 case REP(N, INF): /* as xx{n-1,INF} */
1052 copy = dupl(p, start, finish);
1053 repeat(p, copy, from-1, to);
1055 default: /* "can't happen" */
1056 SETERROR(REG_ASSERT); /* just in case */
1062 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1063 - character from the parse struct, signals a REG_ILLSEQ error if the
1064 - character can't be converted. Returns the number of bytes consumed.
1067 wgetnext(struct parse *p)
1073 memset(&mbs, 0, sizeof(mbs));
1074 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1075 if (n == (size_t)-1 || n == (size_t)-2) {
1076 SETERROR(REG_ILLSEQ);
1086 - seterr - set an error condition
1087 == static int seterr(struct parse *p, int e);
1089 static int /* useless but makes type checking happy */
1090 seterr(struct parse *p, int e)
1092 if (p->error == 0) /* keep earliest error condition */
1094 p->next = nuls; /* try to bring things to a halt */
1096 return(0); /* make the return value well-defined */
1100 - allocset - allocate a set of characters for []
1101 == static cset *allocset(struct parse *p);
1104 allocset(struct parse *p)
1108 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1110 SETERROR(REG_ESPACE);
1114 cs = &p->g->sets[p->g->ncsets++];
1115 memset(cs, 0, sizeof(*cs));
1121 - freeset - free a now-unused set
1122 == static void freeset(struct parse *p, cset *cs);
1125 freeset(struct parse *p, cset *cs)
1127 cset *top = &p->g->sets[p->g->ncsets];
1132 memset(cs, 0, sizeof(*cs));
1133 if (cs == top-1) /* recover only the easy case */
1138 - singleton - Determine whether a set contains only one character,
1139 - returning it if so, otherwise returning OUT.
1146 for (i = n = 0; i < NC; i++)
1153 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1155 return (cs->wides[0]);
1156 /* Don't bother handling the other cases. */
1161 - CHadd - add character to character set.
1164 CHadd(struct parse *p, cset *cs, wint_t ch)
1166 wint_t nch, *newwides;
1169 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1171 newwides = realloc(cs->wides, (cs->nwides + 1) *
1172 sizeof(*cs->wides));
1173 if (newwides == NULL) {
1174 SETERROR(REG_ESPACE);
1177 cs->wides = newwides;
1178 cs->wides[cs->nwides++] = ch;
1181 if ((nch = towlower(ch)) < NC)
1182 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1183 if ((nch = towupper(ch)) < NC)
1184 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1189 - CHaddrange - add all characters in the range [min,max] to a character set.
1192 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1196 for (; min < NC && min <= max; min++)
1200 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1201 sizeof(*cs->ranges));
1202 if (newranges == NULL) {
1203 SETERROR(REG_ESPACE);
1206 cs->ranges = newranges;
1207 cs->ranges[cs->nranges].min = min;
1208 cs->ranges[cs->nranges].min = max;
1213 - CHaddtype - add all characters of a certain type to a character set.
1216 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1221 for (i = 0; i < NC; i++)
1222 if (iswctype(i, wct))
1224 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1225 sizeof(*cs->types));
1226 if (newtypes == NULL) {
1227 SETERROR(REG_ESPACE);
1230 cs->types = newtypes;
1231 cs->types[cs->ntypes++] = wct;
1235 - dupl - emit a duplicate of a bunch of sops
1236 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1238 static sopno /* start of duplicate */
1239 dupl(struct parse *p,
1240 sopno start, /* from here */
1241 sopno finish) /* to this less one */
1244 sopno len = finish - start;
1246 assert(finish >= start);
1249 enlarge(p, p->ssize + len); /* this many unexpected additions */
1250 assert(p->ssize >= p->slen + len);
1251 (void) memcpy((char *)(p->strip + p->slen),
1252 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1258 - doemit - emit a strip operator
1259 == static void doemit(struct parse *p, sop op, size_t opnd);
1261 * It might seem better to implement this as a macro with a function as
1262 * hard-case backup, but it's just too big and messy unless there are
1263 * some changes to the data structures. Maybe later.
1266 doemit(struct parse *p, sop op, size_t opnd)
1268 /* avoid making error situations worse */
1272 /* deal with oversize operands ("can't happen", more or less) */
1273 assert(opnd < 1<<OPSHIFT);
1275 /* deal with undersized strip */
1276 if (p->slen >= p->ssize)
1277 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1278 assert(p->slen < p->ssize);
1280 /* finally, it's all reduced to the easy case */
1281 p->strip[p->slen++] = SOP(op, opnd);
1285 - doinsert - insert a sop into the strip
1286 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1289 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1295 /* avoid making error situations worse */
1300 EMIT(op, opnd); /* do checks, ensure space */
1301 assert(HERE() == sn+1);
1304 /* adjust paren pointers */
1306 for (i = 1; i < NPAREN; i++) {
1307 if (p->pbegin[i] >= pos) {
1310 if (p->pend[i] >= pos) {
1315 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1316 (HERE()-pos-1)*sizeof(sop));
1321 - dofwd - complete a forward reference
1322 == static void dofwd(struct parse *p, sopno pos, sop value);
1325 dofwd(struct parse *p, sopno pos, sop value)
1327 /* avoid making error situations worse */
1331 assert(value < 1<<OPSHIFT);
1332 p->strip[pos] = OP(p->strip[pos]) | value;
1336 - enlarge - enlarge the strip
1337 == static void enlarge(struct parse *p, sopno size);
1340 enlarge(struct parse *p, sopno size)
1344 if (p->ssize >= size)
1347 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1349 SETERROR(REG_ESPACE);
1357 - stripsnug - compact the strip
1358 == static void stripsnug(struct parse *p, struct re_guts *g);
1361 stripsnug(struct parse *p, struct re_guts *g)
1363 g->nstates = p->slen;
1364 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1365 if (g->strip == NULL) {
1366 SETERROR(REG_ESPACE);
1367 g->strip = p->strip;
1372 - findmust - fill in must and mlen with longest mandatory literal string
1373 == static void findmust(struct parse *p, struct re_guts *g);
1375 * This algorithm could do fancy things like analyzing the operands of |
1376 * for common subsequences. Someday. This code is simple and finds most
1377 * of the interesting cases.
1379 * Note that must and mlen got initialized during setup.
1382 findmust(struct parse *p, struct re_guts *g)
1391 char buf[MB_LEN_MAX];
1395 /* avoid making error situations worse */
1400 * It's not generally safe to do a ``char'' substring search on
1401 * multibyte character strings, but it's safe for at least
1402 * UTF-8 (see RFC 3629).
1404 if (MB_CUR_MAX > 1 &&
1405 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1408 /* find the longest OCHAR sequence in strip */
1412 scan = g->strip + 1;
1416 case OCHAR: /* sequence member */
1417 if (newlen == 0) { /* new sequence */
1418 memset(&mbs, 0, sizeof(mbs));
1419 newstart = scan - 1;
1421 clen = wcrtomb(buf, OPND(s), &mbs);
1422 if (clen == (size_t)-1)
1426 case OPLUS_: /* things that don't break one */
1430 case OQUEST_: /* things that must be skipped */
1432 offset = altoffset(scan, offset);
1437 /* assert() interferes w debug printouts */
1438 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1443 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1445 case OBOW: /* things that break a sequence */
1452 if (newlen > g->mlen) { /* ends one */
1456 g->moffset += offset;
1459 g->moffset = offset;
1467 if (newlen > g->mlen) { /* ends one */
1471 g->moffset += offset;
1474 g->moffset = offset;
1483 case OANYOF: /* may or may not invalidate offset */
1484 /* First, everything as OANY */
1485 if (newlen > g->mlen) { /* ends one */
1489 g->moffset += offset;
1492 g->moffset = offset;
1503 /* Anything here makes it impossible or too hard
1504 * to calculate the offset -- so we give up;
1505 * save the last known good offset, in case the
1506 * must sequence doesn't occur later.
1508 if (newlen > g->mlen) { /* ends one */
1512 g->moffset += offset;
1514 g->moffset = offset;
1520 } while (OP(s) != OEND);
1522 if (g->mlen == 0) { /* there isn't one */
1527 /* turn it into a character string */
1528 g->must = malloc((size_t)g->mlen + 1);
1529 if (g->must == NULL) { /* argh; just forget it */
1536 memset(&mbs, 0, sizeof(mbs));
1537 while (cp < g->must + g->mlen) {
1538 while (OP(s = *scan++) != OCHAR)
1540 clen = wcrtomb(cp, OPND(s), &mbs);
1541 assert(clen != (size_t)-1);
1544 assert(cp == g->must + g->mlen);
1545 *cp++ = '\0'; /* just on general principles */
1549 - altoffset - choose biggest offset among multiple choices
1550 == static int altoffset(sop *scan, int offset);
1552 * Compute, recursively if necessary, the largest offset among multiple
1556 altoffset(sop *scan, int offset)
1562 /* If we gave up already on offsets, return */
1569 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1578 try = altoffset(scan, try);
1585 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1588 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1589 /* We must skip to the next position, or we'll
1590 * leave altoffset() too early.
1616 return largest+offset;
1620 - computejumps - compute char jumps for BM scan
1621 == static void computejumps(struct parse *p, struct re_guts *g);
1623 * This algorithm assumes g->must exists and is has size greater than
1624 * zero. It's based on the algorithm found on Computer Algorithms by
1627 * A char jump is the number of characters one needs to jump based on
1628 * the value of the character from the text that was mismatched.
1631 computejumps(struct parse *p, struct re_guts *g)
1636 /* Avoid making errors worse */
1640 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1641 if (g->charjump == NULL) /* Not a fatal error */
1643 /* Adjust for signed chars, if necessary */
1644 g->charjump = &g->charjump[-(CHAR_MIN)];
1646 /* If the character does not exist in the pattern, the jump
1647 * is equal to the number of characters in the pattern.
1649 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1650 g->charjump[ch] = g->mlen;
1652 /* If the character does exist, compute the jump that would
1653 * take us to the last character in the pattern equal to it
1654 * (notice that we match right to left, so that last character
1655 * is the first one that would be matched).
1657 for (mindex = 0; mindex < g->mlen; mindex++)
1658 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1662 - computematchjumps - compute match jumps for BM scan
1663 == static void computematchjumps(struct parse *p, struct re_guts *g);
1665 * This algorithm assumes g->must exists and is has size greater than
1666 * zero. It's based on the algorithm found on Computer Algorithms by
1669 * A match jump is the number of characters one needs to advance based
1670 * on the already-matched suffix.
1671 * Notice that all values here are minus (g->mlen-1), because of the way
1672 * the search algorithm works.
1675 computematchjumps(struct parse *p, struct re_guts *g)
1677 int mindex; /* General "must" iterator */
1678 int suffix; /* Keeps track of matching suffix */
1679 int ssuffix; /* Keeps track of suffixes' suffix */
1680 int* pmatches; /* pmatches[k] points to the next i
1681 * such that i+1...mlen is a substring
1682 * of k+1...k+mlen-i-1
1685 /* Avoid making errors worse */
1689 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1690 if (pmatches == NULL) {
1691 g->matchjump = NULL;
1695 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1696 if (g->matchjump == NULL) /* Not a fatal error */
1699 /* Set maximum possible jump for each character in the pattern */
1700 for (mindex = 0; mindex < g->mlen; mindex++)
1701 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1703 /* Compute pmatches[] */
1704 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1705 mindex--, suffix--) {
1706 pmatches[mindex] = suffix;
1708 /* If a mismatch is found, interrupting the substring,
1709 * compute the matchjump for that position. If no
1710 * mismatch is found, then a text substring mismatched
1711 * against the suffix will also mismatch against the
1714 while (suffix < g->mlen
1715 && g->must[mindex] != g->must[suffix]) {
1716 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1717 g->mlen - mindex - 1);
1718 suffix = pmatches[suffix];
1722 /* Compute the matchjump up to the last substring found to jump
1723 * to the beginning of the largest must pattern prefix matching
1726 for (mindex = 0; mindex <= suffix; mindex++)
1727 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1728 g->mlen + suffix - mindex);
1730 ssuffix = pmatches[suffix];
1731 while (suffix < g->mlen) {
1732 while (suffix <= ssuffix && suffix < g->mlen) {
1733 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1734 g->mlen + ssuffix - suffix);
1737 if (suffix < g->mlen)
1738 ssuffix = pmatches[ssuffix];
1745 - pluscount - count + nesting
1746 == static sopno pluscount(struct parse *p, struct re_guts *g);
1748 static sopno /* nesting depth */
1749 pluscount(struct parse *p, struct re_guts *g)
1757 return(0); /* there may not be an OEND */
1759 scan = g->strip + 1;
1767 if (plusnest > maxnest)
1772 } while (OP(s) != OEND);