2 * This code is derived from OpenBSD's libc/regex, original license follows:
4 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
5 * Copyright (c) 1992, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
38 #include <sys/types.h>
45 #include "regex_impl.h"
50 #include "llvm/Config/config.h"
52 /* character-class table */
53 static struct cclass {
58 { "alnum", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
60 { "alpha", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
62 { "blank", " \t", ""} ,
63 { "cntrl", "\007\b\t\n\v\f\r\1\2\3\4\5\6\16\17\20\21\22\23\24\
64 \25\26\27\30\31\32\33\34\35\36\37\177", ""} ,
65 { "digit", "0123456789", ""} ,
66 { "graph", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
67 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
69 { "lower", "abcdefghijklmnopqrstuvwxyz",
71 { "print", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
72 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ",
74 { "punct", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
76 { "space", "\t\n\v\f\r ", ""} ,
77 { "upper", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
79 { "xdigit", "0123456789ABCDEFabcdef",
84 /* character-name table */
99 { "backspace", '\b' },
105 { "vertical-tab", '\v' },
107 { "form-feed", '\f' },
109 { "carriage-return", '\r' },
133 { "exclamation-mark", '!' },
134 { "quotation-mark", '"' },
135 { "number-sign", '#' },
136 { "dollar-sign", '$' },
137 { "percent-sign", '%' },
138 { "ampersand", '&' },
139 { "apostrophe", '\'' },
140 { "left-parenthesis", '(' },
141 { "right-parenthesis", ')' },
143 { "plus-sign", '+' },
146 { "hyphen-minus", '-' },
148 { "full-stop", '.' },
162 { "semicolon", ';' },
163 { "less-than-sign", '<' },
164 { "equals-sign", '=' },
165 { "greater-than-sign", '>' },
166 { "question-mark", '?' },
167 { "commercial-at", '@' },
168 { "left-square-bracket", '[' },
169 { "backslash", '\\' },
170 { "reverse-solidus", '\\' },
171 { "right-square-bracket", ']' },
172 { "circumflex", '^' },
173 { "circumflex-accent", '^' },
174 { "underscore", '_' },
176 { "grave-accent", '`' },
177 { "left-brace", '{' },
178 { "left-curly-bracket", '{' },
179 { "vertical-line", '|' },
180 { "right-brace", '}' },
181 { "right-curly-bracket", '}' },
188 * parse structure, passed up and down to avoid global variables and
192 char *next; /* next character in RE */
193 char *end; /* end of string (-> NUL normally) */
194 int error; /* has an error been seen? */
195 sop *strip; /* malloced strip */
196 sopno ssize; /* malloced strip size (allocated) */
197 sopno slen; /* malloced strip length (used) */
198 int ncsalloc; /* number of csets allocated */
200 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
201 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
202 sopno pend[NPAREN]; /* -> ) ([0] unused) */
205 static void p_ere(struct parse *, int);
206 static void p_ere_exp(struct parse *);
207 static void p_str(struct parse *);
208 static void p_bre(struct parse *, int, int);
209 static int p_simp_re(struct parse *, int);
210 static int p_count(struct parse *);
211 static void p_bracket(struct parse *);
212 static void p_b_term(struct parse *, cset *);
213 static void p_b_cclass(struct parse *, cset *);
214 static void p_b_eclass(struct parse *, cset *);
215 static char p_b_symbol(struct parse *);
216 static char p_b_coll_elem(struct parse *, int);
217 static char othercase(int);
218 static void bothcases(struct parse *, int);
219 static void ordinary(struct parse *, int);
220 static void nonnewline(struct parse *);
221 static void repeat(struct parse *, sopno, int, int);
222 static int seterr(struct parse *, int);
223 static cset *allocset(struct parse *);
224 static void freeset(struct parse *, cset *);
225 static int freezeset(struct parse *, cset *);
226 static int firstch(struct parse *, cset *);
227 static int nch(struct parse *, cset *);
228 static void mcadd(struct parse *, cset *, const char *);
229 static void mcinvert(struct parse *, cset *);
230 static void mccase(struct parse *, cset *);
231 static int isinsets(struct re_guts *, int);
232 static int samesets(struct re_guts *, int, int);
233 static void categorize(struct parse *, struct re_guts *);
234 static sopno dupl(struct parse *, sopno, sopno);
235 static void doemit(struct parse *, sop, size_t);
236 static void doinsert(struct parse *, sop, size_t, sopno);
237 static void dofwd(struct parse *, sopno, sop);
238 static void enlarge(struct parse *, sopno);
239 static void stripsnug(struct parse *, struct re_guts *);
240 static void findmust(struct parse *, struct re_guts *);
241 static sopno pluscount(struct parse *, struct re_guts *);
243 static char nuls[10]; /* place to point scanner in event of error */
246 * macros for use with parse structure
247 * BEWARE: these know that the parse structure is named `p' !!!
249 #define PEEK() (*p->next)
250 #define PEEK2() (*(p->next+1))
251 #define MORE() (p->next < p->end)
252 #define MORE2() (p->next+1 < p->end)
253 #define SEE(c) (MORE() && PEEK() == (c))
254 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
255 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
256 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
257 #define NEXT() (p->next++)
258 #define NEXT2() (p->next += 2)
259 #define NEXTn(n) (p->next += (n))
260 #define GETNEXT() (*p->next++)
261 #define SETERROR(e) seterr(p, (e))
262 #define REQUIRE(co, e) (void)((co) || SETERROR(e))
263 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
264 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
265 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
266 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
267 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
268 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
269 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
270 #define HERE() (p->slen)
271 #define THERE() (p->slen - 1)
272 #define THERETHERE() (p->slen - 2)
273 #define DROP(n) (p->slen -= (n))
275 #ifdef _POSIX2_RE_DUP_MAX
276 #define DUPMAX _POSIX2_RE_DUP_MAX
280 #define INFINITY (DUPMAX + 1)
283 static int never = 0; /* for use in asserts; shuts lint up */
285 #define never 0 /* some <assert.h>s have bugs too */
289 - llvm_regcomp - interface for parser and compilation
291 int /* 0 success, otherwise REG_something */
292 llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
296 struct parse *p = &pa;
300 # define GOODFLAGS(f) (f)
302 # define GOODFLAGS(f) ((f)&~REG_DUMP)
305 cflags = GOODFLAGS(cflags);
306 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
309 if (cflags®_PEND) {
310 if (preg->re_endp < pattern)
312 len = preg->re_endp - pattern;
314 len = strlen((const char *)pattern);
316 /* do the mallocs early so failure handling is easy */
317 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
318 (NC-1)*sizeof(cat_t));
321 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
322 p->strip = (sop *)calloc(p->ssize, sizeof(sop));
324 if (p->strip == NULL) {
331 p->next = (char *)pattern; /* convenience; we do not modify it */
332 p->end = p->next + len;
335 for (i = 0; i < NPAREN; i++) {
350 g->ncategories = 1; /* category 0 is "everything else" */
351 g->categories = &g->catspace[-(CHAR_MIN)];
352 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
357 g->firststate = THERE();
358 if (cflags®_EXTENDED)
360 else if (cflags®_NOSPEC)
365 g->laststate = THERE();
367 /* tidy up loose ends and fill things in */
371 g->nplus = pluscount(p, g);
373 preg->re_nsub = g->nsub;
375 preg->re_magic = MAGIC1;
377 /* not debugging, so can't rely on the assert() in llvm_regexec() */
378 if (g->iflags®EX_BAD)
379 SETERROR(REG_ASSERT);
382 /* win or lose, we're done */
383 if (p->error != 0) /* lose */
389 - p_ere - ERE parser top level, concatenation and alternation
392 p_ere(struct parse *p, int stop) /* character this ERE should end at */
398 int first = 1; /* is this the first alternative? */
401 /* do a bunch of concatenated expressions */
403 while (MORE() && (c = PEEK()) != '|' && c != stop)
405 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
408 break; /* NOTE BREAK OUT */
411 INSERT(OCH_, conc); /* offset is wrong */
416 ASTERN(OOR1, prevback);
418 AHEAD(prevfwd); /* fix previous offset */
420 EMIT(OOR2, 0); /* offset is very wrong */
423 if (!first) { /* tail-end fixups */
425 ASTERN(O_CH, prevback);
428 assert(!MORE() || SEE(stop));
432 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
435 p_ere_exp(struct parse *p)
445 assert(MORE()); /* caller should have ensured this */
451 REQUIRE(MORE(), REG_EPAREN);
455 p->pbegin[subno] = HERE();
456 EMIT(OLPAREN, subno);
459 if (subno < NPAREN) {
460 p->pend[subno] = HERE();
461 assert(p->pend[subno] != 0);
463 EMIT(ORPAREN, subno);
464 MUSTEAT(')', REG_EPAREN);
466 #ifndef POSIX_MISTAKE
467 case ')': /* happens only if no current unmatched ( */
469 * You may ask, why the ifndef? Because I didn't notice
470 * this until slightly too late for 1003.2, and none of the
471 * other 1003.2 regular-expression reviewers noticed it at
472 * all. So an unmatched ) is legal POSIX, at least until
473 * we can get it fixed.
475 SETERROR(REG_EPAREN);
480 p->g->iflags |= USEBOL;
486 p->g->iflags |= USEEOL;
495 SETERROR(REG_BADRPT);
498 if (p->g->cflags®_NEWLINE)
507 REQUIRE(MORE(), REG_EESCAPE);
509 if (c >= '1' && c <= '9') {
510 /* \[0-9] is taken to be a back-reference to a previously specified
511 * matching group. backrefnum will hold the number. The matching
512 * group must exist (i.e. if \4 is found there must have been at
513 * least 4 matching groups specified in the pattern previously).
515 backrefnum = c - '0';
516 if (p->pend[backrefnum] == 0) {
517 SETERROR(REG_ESUBREG);
521 /* Make sure everything checks out and emit the sequence
522 * that marks a back-reference to the parse structure.
524 assert(backrefnum <= p->g->nsub);
525 EMIT(OBACK_, backrefnum);
526 assert(p->pbegin[backrefnum] != 0);
527 assert(OP(p->strip[p->pbegin[backrefnum]]) != OLPAREN);
528 assert(OP(p->strip[p->pend[backrefnum]]) != ORPAREN);
529 (void) dupl(p, p->pbegin[backrefnum]+1, p->pend[backrefnum]);
530 EMIT(O_BACK, backrefnum);
533 /* Other chars are simply themselves when escaped with a backslash.
538 case '{': /* okay as ordinary except if digit follows */
539 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
549 /* we call { a repetition if followed by a digit */
550 if (!( c == '*' || c == '+' || c == '?' ||
551 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
552 return; /* no repetition, we're done */
555 REQUIRE(!wascaret, REG_BADRPT);
557 case '*': /* implemented as +? */
558 /* this case does not require the (y|) trick, noKLUDGE */
561 INSERT(OQUEST_, pos);
562 ASTERN(O_QUEST, pos);
569 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
570 INSERT(OCH_, pos); /* offset slightly wrong */
571 ASTERN(OOR1, pos); /* this one's right */
572 AHEAD(pos); /* fix the OCH_ */
573 EMIT(OOR2, 0); /* offset very wrong... */
574 AHEAD(THERE()); /* ...so fix it */
575 ASTERN(O_CH, THERETHERE());
580 if (isdigit((uch)PEEK())) {
582 REQUIRE(count <= count2, REG_BADBR);
583 } else /* single number with comma */
585 } else /* just a single number */
587 repeat(p, pos, count, count2);
588 if (!EAT('}')) { /* error heuristics */
589 while (MORE() && PEEK() != '}')
591 REQUIRE(MORE(), REG_EBRACE);
600 if (!( c == '*' || c == '+' || c == '?' ||
601 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
603 SETERROR(REG_BADRPT);
607 - p_str - string (no metacharacters) "parser"
610 p_str(struct parse *p)
612 REQUIRE(MORE(), REG_EMPTY);
614 ordinary(p, GETNEXT());
618 - p_bre - BRE parser top level, anchoring and concatenation
619 * Giving end1 as OUT essentially eliminates the end1/end2 check.
621 * This implementation is a bit of a kludge, in that a trailing $ is first
622 * taken as an ordinary character and then revised to be an anchor. The
623 * only undesirable side effect is that '$' gets included as a character
624 * category in such cases. This is fairly harmless; not worth fixing.
625 * The amount of lookahead needed to avoid this kludge is excessive.
628 p_bre(struct parse *p,
629 int end1, /* first terminating character */
630 int end2) /* second terminating character */
632 sopno start = HERE();
633 int first = 1; /* first subexpression? */
638 p->g->iflags |= USEBOL;
641 while (MORE() && !SEETWO(end1, end2)) {
642 wasdollar = p_simp_re(p, first);
645 if (wasdollar) { /* oops, that was a trailing anchor */
648 p->g->iflags |= USEEOL;
652 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
656 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
658 static int /* was the simple RE an unbackslashed $? */
659 p_simp_re(struct parse *p,
660 int starordinary) /* is a leading * an ordinary character? */
668 # define BACKSL (1<<CHAR_BIT)
670 pos = HERE(); /* repetition op, if any, covers from here */
672 assert(MORE()); /* caller should have ensured this */
675 REQUIRE(MORE(), REG_EESCAPE);
676 c = BACKSL | GETNEXT();
680 if (p->g->cflags®_NEWLINE)
689 SETERROR(REG_BADRPT);
695 p->pbegin[subno] = HERE();
696 EMIT(OLPAREN, subno);
697 /* the MORE here is an error heuristic */
698 if (MORE() && !SEETWO('\\', ')'))
700 if (subno < NPAREN) {
701 p->pend[subno] = HERE();
702 assert(p->pend[subno] != 0);
704 EMIT(ORPAREN, subno);
705 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
707 case BACKSL|')': /* should not get here -- must be user */
709 SETERROR(REG_EPAREN);
720 i = (c&~BACKSL) - '0';
722 if (p->pend[i] != 0) {
723 assert(i <= p->g->nsub);
725 assert(p->pbegin[i] != 0);
726 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
727 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
728 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
731 SETERROR(REG_ESUBREG);
735 REQUIRE(starordinary, REG_BADRPT);
738 ordinary(p, (char)c);
742 if (EAT('*')) { /* implemented as +? */
743 /* this case does not require the (y|) trick, noKLUDGE */
746 INSERT(OQUEST_, pos);
747 ASTERN(O_QUEST, pos);
748 } else if (EATTWO('\\', '{')) {
751 if (MORE() && isdigit((uch)PEEK())) {
753 REQUIRE(count <= count2, REG_BADBR);
754 } else /* single number with comma */
756 } else /* just a single number */
758 repeat(p, pos, count, count2);
759 if (!EATTWO('\\', '}')) { /* error heuristics */
760 while (MORE() && !SEETWO('\\', '}'))
762 REQUIRE(MORE(), REG_EBRACE);
765 } else if (c == '$') /* $ (but not \$) ends it */
772 - p_count - parse a repetition count
774 static int /* the value */
775 p_count(struct parse *p)
780 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
781 count = count*10 + (GETNEXT() - '0');
785 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
790 - p_bracket - parse a bracketed character list
792 * Note a significant property of this code: if the allocset() did SETERROR,
793 * no set operations are done.
796 p_bracket(struct parse *p)
801 /* Dept of Truly Sickening Special-Case Kludges */
802 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
807 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
813 if ((cs = allocset(p)) == NULL) {
814 /* allocset did set error status in p */
819 invert++; /* make note to invert set at end */
824 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
828 MUSTEAT(']', REG_EBRACK);
830 if (p->error != 0) { /* don't mess things up further */
835 if (p->g->cflags®_ICASE) {
839 for (i = p->g->csetsize - 1; i >= 0; i--)
840 if (CHIN(cs, i) && isalpha(i)) {
845 if (cs->multis != NULL)
851 for (i = p->g->csetsize - 1; i >= 0; i--)
856 if (p->g->cflags®_NEWLINE)
858 if (cs->multis != NULL)
862 assert(cs->multis == NULL); /* xxx */
864 if (nch(p, cs) == 1) { /* optimize singleton sets */
865 ordinary(p, firstch(p, cs));
868 EMIT(OANYOF, freezeset(p, cs));
872 - p_b_term - parse one term of a bracketed character list
875 p_b_term(struct parse *p, cset *cs)
881 /* classify what we've got */
882 switch ((MORE()) ? PEEK() : '\0') {
884 c = (MORE2()) ? PEEK2() : '\0';
887 SETERROR(REG_ERANGE);
888 return; /* NOTE RETURN */
896 case ':': /* character class */
898 REQUIRE(MORE(), REG_EBRACK);
900 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
902 REQUIRE(MORE(), REG_EBRACK);
903 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
905 case '=': /* equivalence class */
907 REQUIRE(MORE(), REG_EBRACK);
909 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
911 REQUIRE(MORE(), REG_EBRACK);
912 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
914 default: /* symbol, ordinary character, or range */
915 /* xxx revision needed for multichar stuff */
916 start = p_b_symbol(p);
917 if (SEE('-') && MORE2() && PEEK2() != ']') {
923 finish = p_b_symbol(p);
926 /* xxx what about signed chars here... */
927 REQUIRE(start <= finish, REG_ERANGE);
928 for (i = start; i <= finish; i++)
935 - p_b_cclass - parse a character-class name and deal with it
938 p_b_cclass(struct parse *p, cset *cs)
946 while (MORE() && isalpha((uch)PEEK()))
949 for (cp = cclasses; cp->name != NULL; cp++)
950 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
952 if (cp->name == NULL) {
953 /* oops, didn't find it */
954 SETERROR(REG_ECTYPE);
959 while ((c = *u++) != '\0')
961 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
966 - p_b_eclass - parse an equivalence-class name and deal with it
968 * This implementation is incomplete. xxx
971 p_b_eclass(struct parse *p, cset *cs)
975 c = p_b_coll_elem(p, '=');
980 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
982 static char /* value of symbol */
983 p_b_symbol(struct parse *p)
987 REQUIRE(MORE(), REG_EBRACK);
988 if (!EATTWO('[', '.'))
991 /* collating symbol */
992 value = p_b_coll_elem(p, '.');
993 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
998 - p_b_coll_elem - parse a collating-element name and look it up
1000 static char /* value of collating element */
1001 p_b_coll_elem(struct parse *p,
1002 int endc) /* name ended by endc,']' */
1008 while (MORE() && !SEETWO(endc, ']'))
1011 SETERROR(REG_EBRACK);
1015 for (cp = cnames; cp->name != NULL; cp++)
1016 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1017 return(cp->code); /* known name */
1019 return(*sp); /* single character */
1020 SETERROR(REG_ECOLLATE); /* neither */
1025 - othercase - return the case counterpart of an alphabetic
1027 static char /* if no counterpart, return ch */
1031 assert(isalpha(ch));
1033 return ((uch)tolower(ch));
1034 else if (islower(ch))
1035 return ((uch)toupper(ch));
1036 else /* peculiar, but could happen */
1041 - bothcases - emit a dualcase version of a two-case character
1043 * Boy, is this implementation ever a kludge...
1046 bothcases(struct parse *p, int ch)
1048 char *oldnext = p->next;
1049 char *oldend = p->end;
1053 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1060 assert(p->next == bracket+2);
1066 - ordinary - emit an ordinary character
1069 ordinary(struct parse *p, int ch)
1071 cat_t *cap = p->g->categories;
1073 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
1076 EMIT(OCHAR, (uch)ch);
1078 cap[ch] = p->g->ncategories++;
1083 - nonnewline - emit REG_NEWLINE version of OANY
1085 * Boy, is this implementation ever a kludge...
1088 nonnewline(struct parse *p)
1090 char *oldnext = p->next;
1091 char *oldend = p->end;
1101 assert(p->next == bracket+3);
1107 - repeat - generate code for a bounded repetition, recursively if needed
1110 repeat(struct parse *p,
1111 sopno start, /* operand from here to end of strip */
1112 int from, /* repeated from this number */
1113 int to) /* to this number of times (maybe INFINITY) */
1115 sopno finish = HERE();
1118 # define REP(f, t) ((f)*8 + (t))
1119 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1122 if (p->error != 0) /* head off possible runaway recursion */
1127 switch (REP(MAP(from), MAP(to))) {
1128 case REP(0, 0): /* must be user doing this */
1129 DROP(finish-start); /* drop the operand */
1131 case REP(0, 1): /* as x{1,1}? */
1132 case REP(0, N): /* as x{1,n}? */
1133 case REP(0, INF): /* as x{1,}? */
1134 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1135 INSERT(OCH_, start); /* offset is wrong... */
1136 repeat(p, start+1, 1, to);
1137 ASTERN(OOR1, start);
1138 AHEAD(start); /* ... fix it */
1141 ASTERN(O_CH, THERETHERE());
1143 case REP(1, 1): /* trivial case */
1146 case REP(1, N): /* as x?x{1,n-1} */
1147 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1148 INSERT(OCH_, start);
1149 ASTERN(OOR1, start);
1151 EMIT(OOR2, 0); /* offset very wrong... */
1152 AHEAD(THERE()); /* ...so fix it */
1153 ASTERN(O_CH, THERETHERE());
1154 copy = dupl(p, start+1, finish+1);
1155 assert(copy == finish+4);
1156 repeat(p, copy, 1, to-1);
1158 case REP(1, INF): /* as x+ */
1159 INSERT(OPLUS_, start);
1160 ASTERN(O_PLUS, start);
1162 case REP(N, N): /* as xx{m-1,n-1} */
1163 copy = dupl(p, start, finish);
1164 repeat(p, copy, from-1, to-1);
1166 case REP(N, INF): /* as xx{n-1,INF} */
1167 copy = dupl(p, start, finish);
1168 repeat(p, copy, from-1, to);
1170 default: /* "can't happen" */
1171 SETERROR(REG_ASSERT); /* just in case */
1177 - seterr - set an error condition
1179 static int /* useless but makes type checking happy */
1180 seterr(struct parse *p, int e)
1182 if (p->error == 0) /* keep earliest error condition */
1184 p->next = nuls; /* try to bring things to a halt */
1186 return(0); /* make the return value well-defined */
1190 - allocset - allocate a set of characters for []
1193 allocset(struct parse *p)
1195 int no = p->g->ncsets++;
1199 size_t css = (size_t)p->g->csetsize;
1202 if (no >= p->ncsalloc) { /* need another column of space */
1205 p->ncsalloc += CHAR_BIT;
1207 if (nc > SIZE_MAX / sizeof(cset))
1209 assert(nc % CHAR_BIT == 0);
1210 nbytes = nc / CHAR_BIT * css;
1212 ptr = (cset *)realloc((char *)p->g->sets, nc * sizeof(cset));
1217 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1220 p->g->setbits = ptr;
1222 for (i = 0; i < no; i++)
1223 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1225 (void) memset((char *)p->g->setbits + (nbytes - css), 0, css);
1227 /* XXX should not happen */
1228 if (p->g->sets == NULL || p->g->setbits == NULL)
1231 cs = &p->g->sets[no];
1232 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1233 cs->mask = 1 << ((no) % CHAR_BIT);
1242 free(p->g->setbits);
1243 p->g->setbits = NULL;
1245 SETERROR(REG_ESPACE);
1246 /* caller's responsibility not to do set ops */
1251 - freeset - free a now-unused set
1254 freeset(struct parse *p, cset *cs)
1257 cset *top = &p->g->sets[p->g->ncsets];
1258 size_t css = (size_t)p->g->csetsize;
1260 for (i = 0; i < css; i++)
1262 if (cs == top-1) /* recover only the easy case */
1267 - freezeset - final processing on a set of characters
1269 * The main task here is merging identical sets. This is usually a waste
1270 * of time (although the hash code minimizes the overhead), but can win
1271 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1272 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1275 static int /* set number */
1276 freezeset(struct parse *p, cset *cs)
1280 cset *top = &p->g->sets[p->g->ncsets];
1282 size_t css = (size_t)p->g->csetsize;
1284 /* look for an earlier one which is the same */
1285 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1286 if (cs2->hash == h && cs2 != cs) {
1288 for (i = 0; i < css; i++)
1289 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1295 if (cs2 < top) { /* found one */
1300 return((int)(cs - p->g->sets));
1304 - firstch - return first character in a set (which must have at least one)
1306 static int /* character; there is no "none" value */
1307 firstch(struct parse *p, cset *cs)
1310 size_t css = (size_t)p->g->csetsize;
1312 for (i = 0; i < css; i++)
1316 return(0); /* arbitrary */
1320 - nch - number of characters in a set
1323 nch(struct parse *p, cset *cs)
1326 size_t css = (size_t)p->g->csetsize;
1329 for (i = 0; i < css; i++)
1336 - mcadd - add a collating element to a cset
1339 mcadd( struct parse *p, cset *cs, const char *cp)
1341 size_t oldend = cs->smultis;
1344 cs->smultis += strlen(cp) + 1;
1345 np = realloc(cs->multis, cs->smultis);
1350 SETERROR(REG_ESPACE);
1355 llvm_strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1359 - mcinvert - invert the list of collating elements in a cset
1361 * This would have to know the set of possibilities. Implementation
1366 mcinvert(struct parse *p, cset *cs)
1368 assert(cs->multis == NULL); /* xxx */
1372 - mccase - add case counterparts of the list of collating elements in a cset
1374 * This would have to know the set of possibilities. Implementation
1379 mccase(struct parse *p, cset *cs)
1381 assert(cs->multis == NULL); /* xxx */
1385 - isinsets - is this character in any sets?
1387 static int /* predicate */
1388 isinsets(struct re_guts *g, int c)
1392 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1393 unsigned uc = (uch)c;
1395 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1402 - samesets - are these two characters in exactly the same sets?
1404 static int /* predicate */
1405 samesets(struct re_guts *g, int c1, int c2)
1409 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1410 unsigned uc1 = (uch)c1;
1411 unsigned uc2 = (uch)c2;
1413 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1414 if (col[uc1] != col[uc2])
1420 - categorize - sort out character categories
1423 categorize(struct parse *p, struct re_guts *g)
1425 cat_t *cats = g->categories;
1430 /* avoid making error situations worse */
1434 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1435 if (cats[c] == 0 && isinsets(g, c)) {
1436 cat = g->ncategories++;
1438 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1439 if (cats[c2] == 0 && samesets(g, c, c2))
1445 - dupl - emit a duplicate of a bunch of sops
1447 static sopno /* start of duplicate */
1448 dupl(struct parse *p,
1449 sopno start, /* from here */
1450 sopno finish) /* to this less one */
1453 sopno len = finish - start;
1455 assert(finish >= start);
1458 enlarge(p, p->ssize + len); /* this many unexpected additions */
1459 assert(p->ssize >= p->slen + len);
1460 (void) memmove((char *)(p->strip + p->slen),
1461 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1467 - doemit - emit a strip operator
1469 * It might seem better to implement this as a macro with a function as
1470 * hard-case backup, but it's just too big and messy unless there are
1471 * some changes to the data structures. Maybe later.
1474 doemit(struct parse *p, sop op, size_t opnd)
1476 /* avoid making error situations worse */
1480 /* deal with oversize operands ("can't happen", more or less) */
1481 assert(opnd < 1<<OPSHIFT);
1483 /* deal with undersized strip */
1484 if (p->slen >= p->ssize)
1485 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1486 assert(p->slen < p->ssize);
1488 /* finally, it's all reduced to the easy case */
1489 p->strip[p->slen++] = SOP(op, opnd);
1493 - doinsert - insert a sop into the strip
1496 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1502 /* avoid making error situations worse */
1507 EMIT(op, opnd); /* do checks, ensure space */
1508 assert(HERE() == sn+1);
1511 /* adjust paren pointers */
1513 for (i = 1; i < NPAREN; i++) {
1514 if (p->pbegin[i] >= pos) {
1517 if (p->pend[i] >= pos) {
1522 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1523 (HERE()-pos-1)*sizeof(sop));
1528 - dofwd - complete a forward reference
1531 dofwd(struct parse *p, sopno pos, sop value)
1533 /* avoid making error situations worse */
1537 assert(value < 1<<OPSHIFT);
1538 p->strip[pos] = OP(p->strip[pos]) | value;
1542 - enlarge - enlarge the strip
1545 enlarge(struct parse *p, sopno size)
1549 if (p->ssize >= size)
1552 if ((uintptr_t)size > SIZE_MAX / sizeof(sop)) {
1553 SETERROR(REG_ESPACE);
1557 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1559 SETERROR(REG_ESPACE);
1567 - stripsnug - compact the strip
1570 stripsnug(struct parse *p, struct re_guts *g)
1572 g->nstates = p->slen;
1573 if ((uintptr_t)p->slen > SIZE_MAX / sizeof(sop)) {
1574 g->strip = p->strip;
1575 SETERROR(REG_ESPACE);
1579 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1580 if (g->strip == NULL) {
1581 SETERROR(REG_ESPACE);
1582 g->strip = p->strip;
1587 - findmust - fill in must and mlen with longest mandatory literal string
1589 * This algorithm could do fancy things like analyzing the operands of |
1590 * for common subsequences. Someday. This code is simple and finds most
1591 * of the interesting cases.
1593 * Note that must and mlen got initialized during setup.
1596 findmust(struct parse *p, struct re_guts *g)
1599 sop *start = 0; /* start initialized in the default case, after that */
1600 sop *newstart = 0; /* newstart was initialized in the OCHAR case */
1606 /* avoid making error situations worse */
1610 /* find the longest OCHAR sequence in strip */
1612 scan = g->strip + 1;
1616 case OCHAR: /* sequence member */
1617 if (newlen == 0) /* new sequence */
1618 newstart = scan - 1;
1621 case OPLUS_: /* things that don't break one */
1625 case OQUEST_: /* things that must be skipped */
1631 /* assert() interferes w debug printouts */
1632 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1634 g->iflags |= REGEX_BAD;
1637 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1639 default: /* things that break a sequence */
1640 if (newlen > g->mlen) { /* ends one */
1647 } while (OP(s) != OEND);
1649 if (g->mlen == 0) /* there isn't one */
1652 /* turn it into a character string */
1653 g->must = malloc((size_t)g->mlen + 1);
1654 if (g->must == NULL) { /* argh; just forget it */
1660 for (i = g->mlen; i > 0; i--) {
1661 while (OP(s = *scan++) != OCHAR)
1663 assert(cp < g->must + g->mlen);
1664 *cp++ = (char)OPND(s);
1666 assert(cp == g->must + g->mlen);
1667 *cp++ = '\0'; /* just on general principles */
1671 - pluscount - count + nesting
1673 static sopno /* nesting depth */
1674 pluscount(struct parse *p, struct re_guts *g)
1682 return(0); /* there may not be an OEND */
1684 scan = g->strip + 1;
1692 if (plusnest > maxnest)
1697 } while (OP(s) != OEND);
1699 g->iflags |= REGEX_BAD;