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>
44 #include "regex_impl.h"
49 #include "llvm/Config/config.h"
53 /* Pessimistically bound memory use */
54 #define SIZE_MAX UINT_MAX
57 /* character-class table */
58 static struct cclass {
63 { "alnum", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
65 { "alpha", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
67 { "blank", " \t", ""} ,
68 { "cntrl", "\007\b\t\n\v\f\r\1\2\3\4\5\6\16\17\20\21\22\23\24\
69 \25\26\27\30\31\32\33\34\35\36\37\177", ""} ,
70 { "digit", "0123456789", ""} ,
71 { "graph", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
72 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
74 { "lower", "abcdefghijklmnopqrstuvwxyz",
76 { "print", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
77 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ",
79 { "punct", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
81 { "space", "\t\n\v\f\r ", ""} ,
82 { "upper", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
84 { "xdigit", "0123456789ABCDEFabcdef",
89 /* character-name table */
104 { "backspace", '\b' },
110 { "vertical-tab", '\v' },
112 { "form-feed", '\f' },
114 { "carriage-return", '\r' },
138 { "exclamation-mark", '!' },
139 { "quotation-mark", '"' },
140 { "number-sign", '#' },
141 { "dollar-sign", '$' },
142 { "percent-sign", '%' },
143 { "ampersand", '&' },
144 { "apostrophe", '\'' },
145 { "left-parenthesis", '(' },
146 { "right-parenthesis", ')' },
148 { "plus-sign", '+' },
151 { "hyphen-minus", '-' },
153 { "full-stop", '.' },
167 { "semicolon", ';' },
168 { "less-than-sign", '<' },
169 { "equals-sign", '=' },
170 { "greater-than-sign", '>' },
171 { "question-mark", '?' },
172 { "commercial-at", '@' },
173 { "left-square-bracket", '[' },
174 { "backslash", '\\' },
175 { "reverse-solidus", '\\' },
176 { "right-square-bracket", ']' },
177 { "circumflex", '^' },
178 { "circumflex-accent", '^' },
179 { "underscore", '_' },
181 { "grave-accent", '`' },
182 { "left-brace", '{' },
183 { "left-curly-bracket", '{' },
184 { "vertical-line", '|' },
185 { "right-brace", '}' },
186 { "right-curly-bracket", '}' },
193 * parse structure, passed up and down to avoid global variables and
197 char *next; /* next character in RE */
198 char *end; /* end of string (-> NUL normally) */
199 int error; /* has an error been seen? */
200 sop *strip; /* malloced strip */
201 sopno ssize; /* malloced strip size (allocated) */
202 sopno slen; /* malloced strip length (used) */
203 int ncsalloc; /* number of csets allocated */
205 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
206 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
207 sopno pend[NPAREN]; /* -> ) ([0] unused) */
210 static void p_ere(struct parse *, int);
211 static void p_ere_exp(struct parse *);
212 static void p_str(struct parse *);
213 static void p_bre(struct parse *, int, int);
214 static int p_simp_re(struct parse *, int);
215 static int p_count(struct parse *);
216 static void p_bracket(struct parse *);
217 static void p_b_term(struct parse *, cset *);
218 static void p_b_cclass(struct parse *, cset *);
219 static void p_b_eclass(struct parse *, cset *);
220 static char p_b_symbol(struct parse *);
221 static char p_b_coll_elem(struct parse *, int);
222 static char othercase(int);
223 static void bothcases(struct parse *, int);
224 static void ordinary(struct parse *, int);
225 static void nonnewline(struct parse *);
226 static void repeat(struct parse *, sopno, int, int);
227 static int seterr(struct parse *, int);
228 static cset *allocset(struct parse *);
229 static void freeset(struct parse *, cset *);
230 static int freezeset(struct parse *, cset *);
231 static int firstch(struct parse *, cset *);
232 static int nch(struct parse *, cset *);
233 static void mcadd(struct parse *, cset *, const char *);
234 static void mcinvert(struct parse *, cset *);
235 static void mccase(struct parse *, cset *);
236 static int isinsets(struct re_guts *, int);
237 static int samesets(struct re_guts *, int, int);
238 static void categorize(struct parse *, struct re_guts *);
239 static sopno dupl(struct parse *, sopno, sopno);
240 static void doemit(struct parse *, sop, size_t);
241 static void doinsert(struct parse *, sop, size_t, sopno);
242 static void dofwd(struct parse *, sopno, sop);
243 static void enlarge(struct parse *, sopno);
244 static void stripsnug(struct parse *, struct re_guts *);
245 static void findmust(struct parse *, struct re_guts *);
246 static sopno pluscount(struct parse *, struct re_guts *);
248 static char nuls[10]; /* place to point scanner in event of error */
251 * macros for use with parse structure
252 * BEWARE: these know that the parse structure is named `p' !!!
254 #define PEEK() (*p->next)
255 #define PEEK2() (*(p->next+1))
256 #define MORE() (p->next < p->end)
257 #define MORE2() (p->next+1 < p->end)
258 #define SEE(c) (MORE() && PEEK() == (c))
259 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
260 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
261 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
262 #define NEXT() (p->next++)
263 #define NEXT2() (p->next += 2)
264 #define NEXTn(n) (p->next += (n))
265 #define GETNEXT() (*p->next++)
266 #define SETERROR(e) seterr(p, (e))
267 #define REQUIRE(co, e) (void)((co) || SETERROR(e))
268 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
269 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
270 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
271 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
272 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
273 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
274 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
275 #define HERE() (p->slen)
276 #define THERE() (p->slen - 1)
277 #define THERETHERE() (p->slen - 2)
278 #define DROP(n) (p->slen -= (n))
280 #ifdef _POSIX2_RE_DUP_MAX
281 #define DUPMAX _POSIX2_RE_DUP_MAX
285 #define INFINITY (DUPMAX + 1)
288 static int never = 0; /* for use in asserts; shuts lint up */
290 #define never 0 /* some <assert.h>s have bugs too */
294 - llvm_regcomp - interface for parser and compilation
296 int /* 0 success, otherwise REG_something */
297 llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
301 struct parse *p = &pa;
305 # define GOODFLAGS(f) (f)
307 # define GOODFLAGS(f) ((f)&~REG_DUMP)
310 cflags = GOODFLAGS(cflags);
311 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
314 if (cflags®_PEND) {
315 if (preg->re_endp < pattern)
317 len = preg->re_endp - pattern;
319 len = strlen((const char *)pattern);
321 /* do the mallocs early so failure handling is easy */
322 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
323 (NC-1)*sizeof(cat_t));
326 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
327 p->strip = (sop *)calloc(p->ssize, sizeof(sop));
329 if (p->strip == NULL) {
336 p->next = (char *)pattern; /* convenience; we do not modify it */
337 p->end = p->next + len;
340 for (i = 0; i < NPAREN; i++) {
355 g->ncategories = 1; /* category 0 is "everything else" */
356 g->categories = &g->catspace[-(CHAR_MIN)];
357 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
362 g->firststate = THERE();
363 if (cflags®_EXTENDED)
365 else if (cflags®_NOSPEC)
370 g->laststate = THERE();
372 /* tidy up loose ends and fill things in */
376 g->nplus = pluscount(p, g);
378 preg->re_nsub = g->nsub;
380 preg->re_magic = MAGIC1;
382 /* not debugging, so can't rely on the assert() in llvm_regexec() */
383 if (g->iflags®EX_BAD)
384 SETERROR(REG_ASSERT);
387 /* win or lose, we're done */
388 if (p->error != 0) /* lose */
394 - p_ere - ERE parser top level, concatenation and alternation
397 p_ere(struct parse *p, int stop) /* character this ERE should end at */
403 int first = 1; /* is this the first alternative? */
406 /* do a bunch of concatenated expressions */
408 while (MORE() && (c = PEEK()) != '|' && c != stop)
410 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
413 break; /* NOTE BREAK OUT */
416 INSERT(OCH_, conc); /* offset is wrong */
421 ASTERN(OOR1, prevback);
423 AHEAD(prevfwd); /* fix previous offset */
425 EMIT(OOR2, 0); /* offset is very wrong */
428 if (!first) { /* tail-end fixups */
430 ASTERN(O_CH, prevback);
433 assert(!MORE() || SEE(stop));
437 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
440 p_ere_exp(struct parse *p)
450 assert(MORE()); /* caller should have ensured this */
456 REQUIRE(MORE(), REG_EPAREN);
460 p->pbegin[subno] = HERE();
461 EMIT(OLPAREN, subno);
464 if (subno < NPAREN) {
465 p->pend[subno] = HERE();
466 assert(p->pend[subno] != 0);
468 EMIT(ORPAREN, subno);
469 MUSTEAT(')', REG_EPAREN);
471 #ifndef POSIX_MISTAKE
472 case ')': /* happens only if no current unmatched ( */
474 * You may ask, why the ifndef? Because I didn't notice
475 * this until slightly too late for 1003.2, and none of the
476 * other 1003.2 regular-expression reviewers noticed it at
477 * all. So an unmatched ) is legal POSIX, at least until
478 * we can get it fixed.
480 SETERROR(REG_EPAREN);
485 p->g->iflags |= USEBOL;
491 p->g->iflags |= USEEOL;
500 SETERROR(REG_BADRPT);
503 if (p->g->cflags®_NEWLINE)
512 REQUIRE(MORE(), REG_EESCAPE);
514 if (c >= '1' && c <= '9') {
515 /* \[0-9] is taken to be a back-reference to a previously specified
516 * matching group. backrefnum will hold the number. The matching
517 * group must exist (i.e. if \4 is found there must have been at
518 * least 4 matching groups specified in the pattern previously).
520 backrefnum = c - '0';
521 if (p->pend[backrefnum] == 0) {
522 SETERROR(REG_ESUBREG);
526 /* Make sure everything checks out and emit the sequence
527 * that marks a back-reference to the parse structure.
529 assert(backrefnum <= p->g->nsub);
530 EMIT(OBACK_, backrefnum);
531 assert(p->pbegin[backrefnum] != 0);
532 assert(OP(p->strip[p->pbegin[backrefnum]]) != OLPAREN);
533 assert(OP(p->strip[p->pend[backrefnum]]) != ORPAREN);
534 (void) dupl(p, p->pbegin[backrefnum]+1, p->pend[backrefnum]);
535 EMIT(O_BACK, backrefnum);
538 /* Other chars are simply themselves when escaped with a backslash.
543 case '{': /* okay as ordinary except if digit follows */
544 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
554 /* we call { a repetition if followed by a digit */
555 if (!( c == '*' || c == '+' || c == '?' ||
556 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
557 return; /* no repetition, we're done */
560 REQUIRE(!wascaret, REG_BADRPT);
562 case '*': /* implemented as +? */
563 /* this case does not require the (y|) trick, noKLUDGE */
566 INSERT(OQUEST_, pos);
567 ASTERN(O_QUEST, pos);
574 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
575 INSERT(OCH_, pos); /* offset slightly wrong */
576 ASTERN(OOR1, pos); /* this one's right */
577 AHEAD(pos); /* fix the OCH_ */
578 EMIT(OOR2, 0); /* offset very wrong... */
579 AHEAD(THERE()); /* ...so fix it */
580 ASTERN(O_CH, THERETHERE());
585 if (isdigit((uch)PEEK())) {
587 REQUIRE(count <= count2, REG_BADBR);
588 } else /* single number with comma */
590 } else /* just a single number */
592 repeat(p, pos, count, count2);
593 if (!EAT('}')) { /* error heuristics */
594 while (MORE() && PEEK() != '}')
596 REQUIRE(MORE(), REG_EBRACE);
605 if (!( c == '*' || c == '+' || c == '?' ||
606 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
608 SETERROR(REG_BADRPT);
612 - p_str - string (no metacharacters) "parser"
615 p_str(struct parse *p)
617 REQUIRE(MORE(), REG_EMPTY);
619 ordinary(p, GETNEXT());
623 - p_bre - BRE parser top level, anchoring and concatenation
624 * Giving end1 as OUT essentially eliminates the end1/end2 check.
626 * This implementation is a bit of a kludge, in that a trailing $ is first
627 * taken as an ordinary character and then revised to be an anchor. The
628 * only undesirable side effect is that '$' gets included as a character
629 * category in such cases. This is fairly harmless; not worth fixing.
630 * The amount of lookahead needed to avoid this kludge is excessive.
633 p_bre(struct parse *p,
634 int end1, /* first terminating character */
635 int end2) /* second terminating character */
637 sopno start = HERE();
638 int first = 1; /* first subexpression? */
643 p->g->iflags |= USEBOL;
646 while (MORE() && !SEETWO(end1, end2)) {
647 wasdollar = p_simp_re(p, first);
650 if (wasdollar) { /* oops, that was a trailing anchor */
653 p->g->iflags |= USEEOL;
657 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
661 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
663 static int /* was the simple RE an unbackslashed $? */
664 p_simp_re(struct parse *p,
665 int starordinary) /* is a leading * an ordinary character? */
673 # define BACKSL (1<<CHAR_BIT)
675 pos = HERE(); /* repetition op, if any, covers from here */
677 assert(MORE()); /* caller should have ensured this */
680 REQUIRE(MORE(), REG_EESCAPE);
681 c = BACKSL | GETNEXT();
685 if (p->g->cflags®_NEWLINE)
694 SETERROR(REG_BADRPT);
700 p->pbegin[subno] = HERE();
701 EMIT(OLPAREN, subno);
702 /* the MORE here is an error heuristic */
703 if (MORE() && !SEETWO('\\', ')'))
705 if (subno < NPAREN) {
706 p->pend[subno] = HERE();
707 assert(p->pend[subno] != 0);
709 EMIT(ORPAREN, subno);
710 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
712 case BACKSL|')': /* should not get here -- must be user */
714 SETERROR(REG_EPAREN);
725 i = (c&~BACKSL) - '0';
727 if (p->pend[i] != 0) {
728 assert(i <= p->g->nsub);
730 assert(p->pbegin[i] != 0);
731 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
732 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
733 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
736 SETERROR(REG_ESUBREG);
740 REQUIRE(starordinary, REG_BADRPT);
743 ordinary(p, (char)c);
747 if (EAT('*')) { /* implemented as +? */
748 /* this case does not require the (y|) trick, noKLUDGE */
751 INSERT(OQUEST_, pos);
752 ASTERN(O_QUEST, pos);
753 } else if (EATTWO('\\', '{')) {
756 if (MORE() && isdigit((uch)PEEK())) {
758 REQUIRE(count <= count2, REG_BADBR);
759 } else /* single number with comma */
761 } else /* just a single number */
763 repeat(p, pos, count, count2);
764 if (!EATTWO('\\', '}')) { /* error heuristics */
765 while (MORE() && !SEETWO('\\', '}'))
767 REQUIRE(MORE(), REG_EBRACE);
770 } else if (c == '$') /* $ (but not \$) ends it */
777 - p_count - parse a repetition count
779 static int /* the value */
780 p_count(struct parse *p)
785 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
786 count = count*10 + (GETNEXT() - '0');
790 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
795 - p_bracket - parse a bracketed character list
797 * Note a significant property of this code: if the allocset() did SETERROR,
798 * no set operations are done.
801 p_bracket(struct parse *p)
806 /* Dept of Truly Sickening Special-Case Kludges */
807 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
812 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
818 if ((cs = allocset(p)) == NULL) {
819 /* allocset did set error status in p */
824 invert++; /* make note to invert set at end */
829 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
833 MUSTEAT(']', REG_EBRACK);
835 if (p->error != 0) { /* don't mess things up further */
840 if (p->g->cflags®_ICASE) {
844 for (i = p->g->csetsize - 1; i >= 0; i--)
845 if (CHIN(cs, i) && isalpha(i)) {
850 if (cs->multis != NULL)
856 for (i = p->g->csetsize - 1; i >= 0; i--)
861 if (p->g->cflags®_NEWLINE)
863 if (cs->multis != NULL)
867 assert(cs->multis == NULL); /* xxx */
869 if (nch(p, cs) == 1) { /* optimize singleton sets */
870 ordinary(p, firstch(p, cs));
873 EMIT(OANYOF, freezeset(p, cs));
877 - p_b_term - parse one term of a bracketed character list
880 p_b_term(struct parse *p, cset *cs)
886 /* classify what we've got */
887 switch ((MORE()) ? PEEK() : '\0') {
889 c = (MORE2()) ? PEEK2() : '\0';
892 SETERROR(REG_ERANGE);
893 return; /* NOTE RETURN */
901 case ':': /* character class */
903 REQUIRE(MORE(), REG_EBRACK);
905 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
907 REQUIRE(MORE(), REG_EBRACK);
908 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
910 case '=': /* equivalence class */
912 REQUIRE(MORE(), REG_EBRACK);
914 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
916 REQUIRE(MORE(), REG_EBRACK);
917 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
919 default: /* symbol, ordinary character, or range */
920 /* xxx revision needed for multichar stuff */
921 start = p_b_symbol(p);
922 if (SEE('-') && MORE2() && PEEK2() != ']') {
928 finish = p_b_symbol(p);
931 /* xxx what about signed chars here... */
932 REQUIRE(start <= finish, REG_ERANGE);
933 for (i = start; i <= finish; i++)
940 - p_b_cclass - parse a character-class name and deal with it
943 p_b_cclass(struct parse *p, cset *cs)
951 while (MORE() && isalpha((uch)PEEK()))
954 for (cp = cclasses; cp->name != NULL; cp++)
955 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
957 if (cp->name == NULL) {
958 /* oops, didn't find it */
959 SETERROR(REG_ECTYPE);
964 while ((c = *u++) != '\0')
966 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
971 - p_b_eclass - parse an equivalence-class name and deal with it
973 * This implementation is incomplete. xxx
976 p_b_eclass(struct parse *p, cset *cs)
980 c = p_b_coll_elem(p, '=');
985 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
987 static char /* value of symbol */
988 p_b_symbol(struct parse *p)
992 REQUIRE(MORE(), REG_EBRACK);
993 if (!EATTWO('[', '.'))
996 /* collating symbol */
997 value = p_b_coll_elem(p, '.');
998 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1003 - p_b_coll_elem - parse a collating-element name and look it up
1005 static char /* value of collating element */
1006 p_b_coll_elem(struct parse *p,
1007 int endc) /* name ended by endc,']' */
1013 while (MORE() && !SEETWO(endc, ']'))
1016 SETERROR(REG_EBRACK);
1020 for (cp = cnames; cp->name != NULL; cp++)
1021 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1022 return(cp->code); /* known name */
1024 return(*sp); /* single character */
1025 SETERROR(REG_ECOLLATE); /* neither */
1030 - othercase - return the case counterpart of an alphabetic
1032 static char /* if no counterpart, return ch */
1036 assert(isalpha(ch));
1038 return ((uch)tolower(ch));
1039 else if (islower(ch))
1040 return ((uch)toupper(ch));
1041 else /* peculiar, but could happen */
1046 - bothcases - emit a dualcase version of a two-case character
1048 * Boy, is this implementation ever a kludge...
1051 bothcases(struct parse *p, int ch)
1053 char *oldnext = p->next;
1054 char *oldend = p->end;
1058 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1065 assert(p->next == bracket+2);
1071 - ordinary - emit an ordinary character
1074 ordinary(struct parse *p, int ch)
1076 cat_t *cap = p->g->categories;
1078 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
1081 EMIT(OCHAR, (uch)ch);
1083 cap[ch] = p->g->ncategories++;
1088 - nonnewline - emit REG_NEWLINE version of OANY
1090 * Boy, is this implementation ever a kludge...
1093 nonnewline(struct parse *p)
1095 char *oldnext = p->next;
1096 char *oldend = p->end;
1106 assert(p->next == bracket+3);
1112 - repeat - generate code for a bounded repetition, recursively if needed
1115 repeat(struct parse *p,
1116 sopno start, /* operand from here to end of strip */
1117 int from, /* repeated from this number */
1118 int to) /* to this number of times (maybe INFINITY) */
1120 sopno finish = HERE();
1123 # define REP(f, t) ((f)*8 + (t))
1124 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1127 if (p->error != 0) /* head off possible runaway recursion */
1132 switch (REP(MAP(from), MAP(to))) {
1133 case REP(0, 0): /* must be user doing this */
1134 DROP(finish-start); /* drop the operand */
1136 case REP(0, 1): /* as x{1,1}? */
1137 case REP(0, N): /* as x{1,n}? */
1138 case REP(0, INF): /* as x{1,}? */
1139 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1140 INSERT(OCH_, start); /* offset is wrong... */
1141 repeat(p, start+1, 1, to);
1142 ASTERN(OOR1, start);
1143 AHEAD(start); /* ... fix it */
1146 ASTERN(O_CH, THERETHERE());
1148 case REP(1, 1): /* trivial case */
1151 case REP(1, N): /* as x?x{1,n-1} */
1152 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1153 INSERT(OCH_, start);
1154 ASTERN(OOR1, start);
1156 EMIT(OOR2, 0); /* offset very wrong... */
1157 AHEAD(THERE()); /* ...so fix it */
1158 ASTERN(O_CH, THERETHERE());
1159 copy = dupl(p, start+1, finish+1);
1160 assert(copy == finish+4);
1161 repeat(p, copy, 1, to-1);
1163 case REP(1, INF): /* as x+ */
1164 INSERT(OPLUS_, start);
1165 ASTERN(O_PLUS, start);
1167 case REP(N, N): /* as xx{m-1,n-1} */
1168 copy = dupl(p, start, finish);
1169 repeat(p, copy, from-1, to-1);
1171 case REP(N, INF): /* as xx{n-1,INF} */
1172 copy = dupl(p, start, finish);
1173 repeat(p, copy, from-1, to);
1175 default: /* "can't happen" */
1176 SETERROR(REG_ASSERT); /* just in case */
1182 - seterr - set an error condition
1184 static int /* useless but makes type checking happy */
1185 seterr(struct parse *p, int e)
1187 if (p->error == 0) /* keep earliest error condition */
1189 p->next = nuls; /* try to bring things to a halt */
1191 return(0); /* make the return value well-defined */
1195 - allocset - allocate a set of characters for []
1198 allocset(struct parse *p)
1200 int no = p->g->ncsets++;
1204 size_t css = (size_t)p->g->csetsize;
1207 if (no >= p->ncsalloc) { /* need another column of space */
1210 p->ncsalloc += CHAR_BIT;
1212 if (nc > SIZE_MAX / sizeof(cset))
1214 assert(nc % CHAR_BIT == 0);
1215 nbytes = nc / CHAR_BIT * css;
1217 ptr = (cset *)realloc((char *)p->g->sets, nc * sizeof(cset));
1222 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1225 p->g->setbits = ptr;
1227 for (i = 0; i < no; i++)
1228 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1230 (void) memset((char *)p->g->setbits + (nbytes - css), 0, css);
1232 /* XXX should not happen */
1233 if (p->g->sets == NULL || p->g->setbits == NULL)
1236 cs = &p->g->sets[no];
1237 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1238 cs->mask = 1 << ((no) % CHAR_BIT);
1247 free(p->g->setbits);
1248 p->g->setbits = NULL;
1250 SETERROR(REG_ESPACE);
1251 /* caller's responsibility not to do set ops */
1256 - freeset - free a now-unused set
1259 freeset(struct parse *p, cset *cs)
1262 cset *top = &p->g->sets[p->g->ncsets];
1263 size_t css = (size_t)p->g->csetsize;
1265 for (i = 0; i < css; i++)
1267 if (cs == top-1) /* recover only the easy case */
1272 - freezeset - final processing on a set of characters
1274 * The main task here is merging identical sets. This is usually a waste
1275 * of time (although the hash code minimizes the overhead), but can win
1276 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1277 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1280 static int /* set number */
1281 freezeset(struct parse *p, cset *cs)
1285 cset *top = &p->g->sets[p->g->ncsets];
1287 size_t css = (size_t)p->g->csetsize;
1289 /* look for an earlier one which is the same */
1290 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1291 if (cs2->hash == h && cs2 != cs) {
1293 for (i = 0; i < css; i++)
1294 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1300 if (cs2 < top) { /* found one */
1305 return((int)(cs - p->g->sets));
1309 - firstch - return first character in a set (which must have at least one)
1311 static int /* character; there is no "none" value */
1312 firstch(struct parse *p, cset *cs)
1315 size_t css = (size_t)p->g->csetsize;
1317 for (i = 0; i < css; i++)
1321 return(0); /* arbitrary */
1325 - nch - number of characters in a set
1328 nch(struct parse *p, cset *cs)
1331 size_t css = (size_t)p->g->csetsize;
1334 for (i = 0; i < css; i++)
1341 - mcadd - add a collating element to a cset
1344 mcadd( struct parse *p, cset *cs, const char *cp)
1346 size_t oldend = cs->smultis;
1349 cs->smultis += strlen(cp) + 1;
1350 np = realloc(cs->multis, cs->smultis);
1355 SETERROR(REG_ESPACE);
1360 llvm_strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1364 - mcinvert - invert the list of collating elements in a cset
1366 * This would have to know the set of possibilities. Implementation
1371 mcinvert(struct parse *p, cset *cs)
1373 assert(cs->multis == NULL); /* xxx */
1377 - mccase - add case counterparts of the list of collating elements in a cset
1379 * This would have to know the set of possibilities. Implementation
1384 mccase(struct parse *p, cset *cs)
1386 assert(cs->multis == NULL); /* xxx */
1390 - isinsets - is this character in any sets?
1392 static int /* predicate */
1393 isinsets(struct re_guts *g, int c)
1397 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1398 unsigned uc = (uch)c;
1400 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1407 - samesets - are these two characters in exactly the same sets?
1409 static int /* predicate */
1410 samesets(struct re_guts *g, int c1, int c2)
1414 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1415 unsigned uc1 = (uch)c1;
1416 unsigned uc2 = (uch)c2;
1418 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1419 if (col[uc1] != col[uc2])
1425 - categorize - sort out character categories
1428 categorize(struct parse *p, struct re_guts *g)
1430 cat_t *cats = g->categories;
1435 /* avoid making error situations worse */
1439 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1440 if (cats[c] == 0 && isinsets(g, c)) {
1441 cat = g->ncategories++;
1443 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1444 if (cats[c2] == 0 && samesets(g, c, c2))
1450 - dupl - emit a duplicate of a bunch of sops
1452 static sopno /* start of duplicate */
1453 dupl(struct parse *p,
1454 sopno start, /* from here */
1455 sopno finish) /* to this less one */
1458 sopno len = finish - start;
1460 assert(finish >= start);
1463 enlarge(p, p->ssize + len); /* this many unexpected additions */
1464 assert(p->ssize >= p->slen + len);
1465 (void) memmove((char *)(p->strip + p->slen),
1466 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1472 - doemit - emit a strip operator
1474 * It might seem better to implement this as a macro with a function as
1475 * hard-case backup, but it's just too big and messy unless there are
1476 * some changes to the data structures. Maybe later.
1479 doemit(struct parse *p, sop op, size_t opnd)
1481 /* avoid making error situations worse */
1485 /* deal with oversize operands ("can't happen", more or less) */
1486 assert(opnd < 1<<OPSHIFT);
1488 /* deal with undersized strip */
1489 if (p->slen >= p->ssize)
1490 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1491 assert(p->slen < p->ssize);
1493 /* finally, it's all reduced to the easy case */
1494 p->strip[p->slen++] = SOP(op, opnd);
1498 - doinsert - insert a sop into the strip
1501 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1507 /* avoid making error situations worse */
1512 EMIT(op, opnd); /* do checks, ensure space */
1513 assert(HERE() == sn+1);
1516 /* adjust paren pointers */
1518 for (i = 1; i < NPAREN; i++) {
1519 if (p->pbegin[i] >= pos) {
1522 if (p->pend[i] >= pos) {
1527 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1528 (HERE()-pos-1)*sizeof(sop));
1533 - dofwd - complete a forward reference
1536 dofwd(struct parse *p, sopno pos, sop value)
1538 /* avoid making error situations worse */
1542 assert(value < 1<<OPSHIFT);
1543 p->strip[pos] = OP(p->strip[pos]) | value;
1547 - enlarge - enlarge the strip
1550 enlarge(struct parse *p, sopno size)
1554 if (p->ssize >= size)
1557 if ((uintptr_t)size > SIZE_MAX / sizeof(sop)) {
1558 SETERROR(REG_ESPACE);
1562 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1564 SETERROR(REG_ESPACE);
1572 - stripsnug - compact the strip
1575 stripsnug(struct parse *p, struct re_guts *g)
1577 g->nstates = p->slen;
1578 if ((uintptr_t)p->slen > SIZE_MAX / sizeof(sop)) {
1579 g->strip = p->strip;
1580 SETERROR(REG_ESPACE);
1584 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1585 if (g->strip == NULL) {
1586 SETERROR(REG_ESPACE);
1587 g->strip = p->strip;
1592 - findmust - fill in must and mlen with longest mandatory literal string
1594 * This algorithm could do fancy things like analyzing the operands of |
1595 * for common subsequences. Someday. This code is simple and finds most
1596 * of the interesting cases.
1598 * Note that must and mlen got initialized during setup.
1601 findmust(struct parse *p, struct re_guts *g)
1604 sop *start = 0; /* start initialized in the default case, after that */
1605 sop *newstart = 0; /* newstart was initialized in the OCHAR case */
1611 /* avoid making error situations worse */
1615 /* find the longest OCHAR sequence in strip */
1617 scan = g->strip + 1;
1621 case OCHAR: /* sequence member */
1622 if (newlen == 0) /* new sequence */
1623 newstart = scan - 1;
1626 case OPLUS_: /* things that don't break one */
1630 case OQUEST_: /* things that must be skipped */
1636 /* assert() interferes w debug printouts */
1637 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1639 g->iflags |= REGEX_BAD;
1642 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1644 default: /* things that break a sequence */
1645 if (newlen > g->mlen) { /* ends one */
1652 } while (OP(s) != OEND);
1654 if (g->mlen == 0) /* there isn't one */
1657 /* turn it into a character string */
1658 g->must = malloc((size_t)g->mlen + 1);
1659 if (g->must == NULL) { /* argh; just forget it */
1665 for (i = g->mlen; i > 0; i--) {
1666 while (OP(s = *scan++) != OCHAR)
1668 assert(cp < g->must + g->mlen);
1669 *cp++ = (char)OPND(s);
1671 assert(cp == g->must + g->mlen);
1672 *cp++ = '\0'; /* just on general principles */
1676 - pluscount - count + nesting
1678 static sopno /* nesting depth */
1679 pluscount(struct parse *p, struct re_guts *g)
1687 return(0); /* there may not be an OEND */
1689 scan = g->strip + 1;
1697 if (plusnest > maxnest)
1702 } while (OP(s) != OEND);
1704 g->iflags |= REGEX_BAD;