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"
51 #include "llvm/Support/Compiler.h"
53 /* character-class table */
54 static struct cclass {
59 { "alnum", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
61 { "alpha", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
63 { "blank", " \t", ""} ,
64 { "cntrl", "\007\b\t\n\v\f\r\1\2\3\4\5\6\16\17\20\21\22\23\24\
65 \25\26\27\30\31\32\33\34\35\36\37\177", ""} ,
66 { "digit", "0123456789", ""} ,
67 { "graph", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
68 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
70 { "lower", "abcdefghijklmnopqrstuvwxyz",
72 { "print", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
73 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ",
75 { "punct", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
77 { "space", "\t\n\v\f\r ", ""} ,
78 { "upper", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
80 { "xdigit", "0123456789ABCDEFabcdef",
85 /* character-name table */
100 { "backspace", '\b' },
106 { "vertical-tab", '\v' },
108 { "form-feed", '\f' },
110 { "carriage-return", '\r' },
134 { "exclamation-mark", '!' },
135 { "quotation-mark", '"' },
136 { "number-sign", '#' },
137 { "dollar-sign", '$' },
138 { "percent-sign", '%' },
139 { "ampersand", '&' },
140 { "apostrophe", '\'' },
141 { "left-parenthesis", '(' },
142 { "right-parenthesis", ')' },
144 { "plus-sign", '+' },
147 { "hyphen-minus", '-' },
149 { "full-stop", '.' },
163 { "semicolon", ';' },
164 { "less-than-sign", '<' },
165 { "equals-sign", '=' },
166 { "greater-than-sign", '>' },
167 { "question-mark", '?' },
168 { "commercial-at", '@' },
169 { "left-square-bracket", '[' },
170 { "backslash", '\\' },
171 { "reverse-solidus", '\\' },
172 { "right-square-bracket", ']' },
173 { "circumflex", '^' },
174 { "circumflex-accent", '^' },
175 { "underscore", '_' },
177 { "grave-accent", '`' },
178 { "left-brace", '{' },
179 { "left-curly-bracket", '{' },
180 { "vertical-line", '|' },
181 { "right-brace", '}' },
182 { "right-curly-bracket", '}' },
189 * parse structure, passed up and down to avoid global variables and
193 char *next; /* next character in RE */
194 char *end; /* end of string (-> NUL normally) */
195 int error; /* has an error been seen? */
196 sop *strip; /* malloced strip */
197 sopno ssize; /* malloced strip size (allocated) */
198 sopno slen; /* malloced strip length (used) */
199 int ncsalloc; /* number of csets allocated */
201 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
202 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
203 sopno pend[NPAREN]; /* -> ) ([0] unused) */
206 static void p_ere(struct parse *, int);
207 static void p_ere_exp(struct parse *);
208 static void p_str(struct parse *);
209 static void p_bre(struct parse *, int, int);
210 static int p_simp_re(struct parse *, int);
211 static int p_count(struct parse *);
212 static void p_bracket(struct parse *);
213 static void p_b_term(struct parse *, cset *);
214 static void p_b_cclass(struct parse *, cset *);
215 static void p_b_eclass(struct parse *, cset *);
216 static char p_b_symbol(struct parse *);
217 static char p_b_coll_elem(struct parse *, int);
218 static char othercase(int);
219 static void bothcases(struct parse *, int);
220 static void ordinary(struct parse *, int);
221 static void nonnewline(struct parse *);
222 static void repeat(struct parse *, sopno, int, int);
223 static int seterr(struct parse *, int);
224 static cset *allocset(struct parse *);
225 static void freeset(struct parse *, cset *);
226 static int freezeset(struct parse *, cset *);
227 static int firstch(struct parse *, cset *);
228 static int nch(struct parse *, cset *);
229 static void mcadd(struct parse *, cset *, const char *);
230 static void mcinvert(struct parse *, cset *);
231 static void mccase(struct parse *, cset *);
232 static int isinsets(struct re_guts *, int);
233 static int samesets(struct re_guts *, int, int);
234 static void categorize(struct parse *, struct re_guts *);
235 static sopno dupl(struct parse *, sopno, sopno);
236 static void doemit(struct parse *, sop, size_t);
237 static void doinsert(struct parse *, sop, size_t, sopno);
238 static void dofwd(struct parse *, sopno, sop);
239 static void enlarge(struct parse *, sopno);
240 static void stripsnug(struct parse *, struct re_guts *);
241 static void findmust(struct parse *, struct re_guts *);
242 static sopno pluscount(struct parse *, struct re_guts *);
244 static char nuls[10]; /* place to point scanner in event of error */
247 * macros for use with parse structure
248 * BEWARE: these know that the parse structure is named `p' !!!
250 #define PEEK() (*p->next)
251 #define PEEK2() (*(p->next+1))
252 #define MORE() (p->end - p->next > 0)
253 #define MORE2() (p->end - p->next > 1)
254 #define SEE(c) (MORE() && PEEK() == (c))
255 #define SEETWO(a, b) (MORE2() && PEEK() == (a) && PEEK2() == (b))
256 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
257 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
258 #define NEXT() (p->next++)
259 #define NEXT2() (p->next += 2)
260 #define NEXTn(n) (p->next += (n))
261 #define GETNEXT() (*p->next++)
262 #define SETERROR(e) seterr(p, (e))
263 #define REQUIRE(co, e) (void)((co) || SETERROR(e))
264 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
265 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
266 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
267 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
268 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
269 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
270 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
271 #define HERE() (p->slen)
272 #define THERE() (p->slen - 1)
273 #define THERETHERE() (p->slen - 2)
274 #define DROP(n) (p->slen -= (n))
276 #ifdef _POSIX2_RE_DUP_MAX
277 #define DUPMAX _POSIX2_RE_DUP_MAX
281 #define INFINITY (DUPMAX + 1)
284 static int never = 0; /* for use in asserts; shuts lint up */
286 #define never 0 /* some <assert.h>s have bugs too */
290 - llvm_regcomp - interface for parser and compilation
292 int /* 0 success, otherwise REG_something */
293 llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
297 struct parse *p = &pa;
301 # define GOODFLAGS(f) (f)
303 # define GOODFLAGS(f) ((f)&~REG_DUMP)
306 cflags = GOODFLAGS(cflags);
307 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
310 if (cflags®_PEND) {
311 if (preg->re_endp < pattern)
313 len = preg->re_endp - pattern;
315 len = strlen((const char *)pattern);
317 /* do the mallocs early so failure handling is easy */
318 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
319 (NC-1)*sizeof(cat_t));
322 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
323 p->strip = (sop *)calloc(p->ssize, sizeof(sop));
325 if (p->strip == NULL) {
332 /* suppress warning from the following explicit cast. */
334 #pragma GCC diagnostic push
335 #pragma GCC diagnostic ignored "-Wcast-qual"
336 #endif /* __GNUC__ */
337 p->next = (char *)pattern; /* convenience; we do not modify it */
339 #pragma GCC diagnostic pop
340 #endif /* __GNUC__ */
341 p->end = p->next + len;
344 for (i = 0; i < NPAREN; i++) {
359 g->ncategories = 1; /* category 0 is "everything else" */
360 g->categories = &g->catspace[-(CHAR_MIN)];
361 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
366 g->firststate = THERE();
367 if (cflags®_EXTENDED)
369 else if (cflags®_NOSPEC)
374 g->laststate = THERE();
376 /* tidy up loose ends and fill things in */
380 g->nplus = pluscount(p, g);
382 preg->re_nsub = g->nsub;
384 preg->re_magic = MAGIC1;
386 /* not debugging, so can't rely on the assert() in llvm_regexec() */
387 if (g->iflags®EX_BAD)
388 SETERROR(REG_ASSERT);
391 /* win or lose, we're done */
392 if (p->error != 0) /* lose */
398 - p_ere - ERE parser top level, concatenation and alternation
401 p_ere(struct parse *p, int stop) /* character this ERE should end at */
407 int first = 1; /* is this the first alternative? */
410 /* do a bunch of concatenated expressions */
412 while (MORE() && (c = PEEK()) != '|' && c != stop)
414 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
417 break; /* NOTE BREAK OUT */
420 INSERT(OCH_, conc); /* offset is wrong */
425 ASTERN(OOR1, prevback);
427 AHEAD(prevfwd); /* fix previous offset */
429 EMIT(OOR2, 0); /* offset is very wrong */
432 if (!first) { /* tail-end fixups */
434 ASTERN(O_CH, prevback);
437 assert(!MORE() || SEE(stop));
441 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
444 p_ere_exp(struct parse *p)
454 assert(MORE()); /* caller should have ensured this */
460 REQUIRE(MORE(), REG_EPAREN);
464 p->pbegin[subno] = HERE();
465 EMIT(OLPAREN, subno);
468 if (subno < NPAREN) {
469 p->pend[subno] = HERE();
470 assert(p->pend[subno] != 0);
472 EMIT(ORPAREN, subno);
473 MUSTEAT(')', REG_EPAREN);
475 #ifndef POSIX_MISTAKE
476 case ')': /* happens only if no current unmatched ( */
478 * You may ask, why the ifndef? Because I didn't notice
479 * this until slightly too late for 1003.2, and none of the
480 * other 1003.2 regular-expression reviewers noticed it at
481 * all. So an unmatched ) is legal POSIX, at least until
482 * we can get it fixed.
484 SETERROR(REG_EPAREN);
489 p->g->iflags |= USEBOL;
495 p->g->iflags |= USEEOL;
504 SETERROR(REG_BADRPT);
507 if (p->g->cflags®_NEWLINE)
516 REQUIRE(MORE(), REG_EESCAPE);
518 if (c >= '1' && c <= '9') {
519 /* \[0-9] is taken to be a back-reference to a previously specified
520 * matching group. backrefnum will hold the number. The matching
521 * group must exist (i.e. if \4 is found there must have been at
522 * least 4 matching groups specified in the pattern previously).
524 backrefnum = c - '0';
525 if (p->pend[backrefnum] == 0) {
526 SETERROR(REG_ESUBREG);
530 /* Make sure everything checks out and emit the sequence
531 * that marks a back-reference to the parse structure.
533 assert(backrefnum <= p->g->nsub);
534 EMIT(OBACK_, backrefnum);
535 assert(p->pbegin[backrefnum] != 0);
536 assert(OP(p->strip[p->pbegin[backrefnum]]) == OLPAREN);
537 assert(OP(p->strip[p->pend[backrefnum]]) == ORPAREN);
538 (void) dupl(p, p->pbegin[backrefnum]+1, p->pend[backrefnum]);
539 EMIT(O_BACK, backrefnum);
542 /* Other chars are simply themselves when escaped with a backslash.
547 case '{': /* okay as ordinary except if digit follows */
548 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
558 /* we call { a repetition if followed by a digit */
559 if (!( c == '*' || c == '+' || c == '?' ||
560 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
561 return; /* no repetition, we're done */
564 REQUIRE(!wascaret, REG_BADRPT);
566 case '*': /* implemented as +? */
567 /* this case does not require the (y|) trick, noKLUDGE */
570 INSERT(OQUEST_, pos);
571 ASTERN(O_QUEST, pos);
578 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
579 INSERT(OCH_, pos); /* offset slightly wrong */
580 ASTERN(OOR1, pos); /* this one's right */
581 AHEAD(pos); /* fix the OCH_ */
582 EMIT(OOR2, 0); /* offset very wrong... */
583 AHEAD(THERE()); /* ...so fix it */
584 ASTERN(O_CH, THERETHERE());
589 if (isdigit((uch)PEEK())) {
591 REQUIRE(count <= count2, REG_BADBR);
592 } else /* single number with comma */
594 } else /* just a single number */
596 repeat(p, pos, count, count2);
597 if (!EAT('}')) { /* error heuristics */
598 while (MORE() && PEEK() != '}')
600 REQUIRE(MORE(), REG_EBRACE);
609 if (!( c == '*' || c == '+' || c == '?' ||
610 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
612 SETERROR(REG_BADRPT);
616 - p_str - string (no metacharacters) "parser"
619 p_str(struct parse *p)
621 REQUIRE(MORE(), REG_EMPTY);
623 ordinary(p, GETNEXT());
627 - p_bre - BRE parser top level, anchoring and concatenation
628 * Giving end1 as OUT essentially eliminates the end1/end2 check.
630 * This implementation is a bit of a kludge, in that a trailing $ is first
631 * taken as an ordinary character and then revised to be an anchor. The
632 * only undesirable side effect is that '$' gets included as a character
633 * category in such cases. This is fairly harmless; not worth fixing.
634 * The amount of lookahead needed to avoid this kludge is excessive.
637 p_bre(struct parse *p,
638 int end1, /* first terminating character */
639 int end2) /* second terminating character */
641 sopno start = HERE();
642 int first = 1; /* first subexpression? */
647 p->g->iflags |= USEBOL;
650 while (MORE() && !SEETWO(end1, end2)) {
651 wasdollar = p_simp_re(p, first);
654 if (wasdollar) { /* oops, that was a trailing anchor */
657 p->g->iflags |= USEEOL;
661 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
665 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
667 static int /* was the simple RE an unbackslashed $? */
668 p_simp_re(struct parse *p,
669 int starordinary) /* is a leading * an ordinary character? */
677 # define BACKSL (1<<CHAR_BIT)
679 pos = HERE(); /* repetition op, if any, covers from here */
681 assert(MORE()); /* caller should have ensured this */
684 REQUIRE(MORE(), REG_EESCAPE);
685 c = BACKSL | GETNEXT();
689 if (p->g->cflags®_NEWLINE)
698 SETERROR(REG_BADRPT);
704 p->pbegin[subno] = HERE();
705 EMIT(OLPAREN, subno);
706 /* the MORE here is an error heuristic */
707 if (MORE() && !SEETWO('\\', ')'))
709 if (subno < NPAREN) {
710 p->pend[subno] = HERE();
711 assert(p->pend[subno] != 0);
713 EMIT(ORPAREN, subno);
714 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
716 case BACKSL|')': /* should not get here -- must be user */
718 SETERROR(REG_EPAREN);
729 i = (c&~BACKSL) - '0';
731 if (p->pend[i] != 0) {
732 assert(i <= p->g->nsub);
734 assert(p->pbegin[i] != 0);
735 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
736 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
737 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
740 SETERROR(REG_ESUBREG);
744 REQUIRE(starordinary, REG_BADRPT);
747 ordinary(p, (char)c);
751 if (EAT('*')) { /* implemented as +? */
752 /* this case does not require the (y|) trick, noKLUDGE */
755 INSERT(OQUEST_, pos);
756 ASTERN(O_QUEST, pos);
757 } else if (EATTWO('\\', '{')) {
760 if (MORE() && isdigit((uch)PEEK())) {
762 REQUIRE(count <= count2, REG_BADBR);
763 } else /* single number with comma */
765 } else /* just a single number */
767 repeat(p, pos, count, count2);
768 if (!EATTWO('\\', '}')) { /* error heuristics */
769 while (MORE() && !SEETWO('\\', '}'))
771 REQUIRE(MORE(), REG_EBRACE);
774 } else if (c == '$') /* $ (but not \$) ends it */
781 - p_count - parse a repetition count
783 static int /* the value */
784 p_count(struct parse *p)
789 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
790 count = count*10 + (GETNEXT() - '0');
794 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
799 - p_bracket - parse a bracketed character list
801 * Note a significant property of this code: if the allocset() did SETERROR,
802 * no set operations are done.
805 p_bracket(struct parse *p)
810 /* Dept of Truly Sickening Special-Case Kludges */
811 if (p->end - p->next > 5) {
812 if (strncmp(p->next, "[:<:]]", 6) == 0) {
817 if (strncmp(p->next, "[:>:]]", 6) == 0) {
824 if ((cs = allocset(p)) == NULL) {
825 /* allocset did set error status in p */
830 invert++; /* make note to invert set at end */
835 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
839 MUSTEAT(']', REG_EBRACK);
841 if (p->error != 0) { /* don't mess things up further */
846 if (p->g->cflags®_ICASE) {
850 for (i = p->g->csetsize - 1; i >= 0; i--)
851 if (CHIN(cs, i) && isalpha(i)) {
856 if (cs->multis != NULL)
862 for (i = p->g->csetsize - 1; i >= 0; i--)
867 if (p->g->cflags®_NEWLINE)
869 if (cs->multis != NULL)
873 assert(cs->multis == NULL); /* xxx */
875 if (nch(p, cs) == 1) { /* optimize singleton sets */
876 ordinary(p, firstch(p, cs));
879 EMIT(OANYOF, freezeset(p, cs));
883 - p_b_term - parse one term of a bracketed character list
886 p_b_term(struct parse *p, cset *cs)
892 /* classify what we've got */
893 switch ((MORE()) ? PEEK() : '\0') {
895 c = (MORE2()) ? PEEK2() : '\0';
898 SETERROR(REG_ERANGE);
899 return; /* NOTE RETURN */
907 case ':': /* character class */
909 REQUIRE(MORE(), REG_EBRACK);
911 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
913 REQUIRE(MORE(), REG_EBRACK);
914 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
916 case '=': /* equivalence class */
918 REQUIRE(MORE(), REG_EBRACK);
920 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
922 REQUIRE(MORE(), REG_EBRACK);
923 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
925 default: /* symbol, ordinary character, or range */
926 /* xxx revision needed for multichar stuff */
927 start = p_b_symbol(p);
928 if (SEE('-') && MORE2() && PEEK2() != ']') {
934 finish = p_b_symbol(p);
937 /* xxx what about signed chars here... */
938 REQUIRE(start <= finish, REG_ERANGE);
939 for (i = start; i <= finish; i++)
946 - p_b_cclass - parse a character-class name and deal with it
949 p_b_cclass(struct parse *p, cset *cs)
957 while (MORE() && isalpha((uch)PEEK()))
960 for (cp = cclasses; cp->name != NULL; cp++)
961 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
963 if (cp->name == NULL) {
964 /* oops, didn't find it */
965 SETERROR(REG_ECTYPE);
970 while ((c = *u++) != '\0')
972 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
977 - p_b_eclass - parse an equivalence-class name and deal with it
979 * This implementation is incomplete. xxx
982 p_b_eclass(struct parse *p, cset *cs)
986 c = p_b_coll_elem(p, '=');
991 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
993 static char /* value of symbol */
994 p_b_symbol(struct parse *p)
998 REQUIRE(MORE(), REG_EBRACK);
999 if (!EATTWO('[', '.'))
1002 /* collating symbol */
1003 value = p_b_coll_elem(p, '.');
1004 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1009 - p_b_coll_elem - parse a collating-element name and look it up
1011 static char /* value of collating element */
1012 p_b_coll_elem(struct parse *p,
1013 int endc) /* name ended by endc,']' */
1019 while (MORE() && !SEETWO(endc, ']'))
1022 SETERROR(REG_EBRACK);
1026 for (cp = cnames; cp->name != NULL; cp++)
1027 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1028 return(cp->code); /* known name */
1030 return(*sp); /* single character */
1031 SETERROR(REG_ECOLLATE); /* neither */
1036 - othercase - return the case counterpart of an alphabetic
1038 static char /* if no counterpart, return ch */
1042 assert(isalpha(ch));
1044 return ((uch)tolower(ch));
1045 else if (islower(ch))
1046 return ((uch)toupper(ch));
1047 else /* peculiar, but could happen */
1052 - bothcases - emit a dualcase version of a two-case character
1054 * Boy, is this implementation ever a kludge...
1057 bothcases(struct parse *p, int ch)
1059 char *oldnext = p->next;
1060 char *oldend = p->end;
1064 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1071 assert(p->next == bracket+2);
1077 - ordinary - emit an ordinary character
1080 ordinary(struct parse *p, int ch)
1082 cat_t *cap = p->g->categories;
1084 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
1087 EMIT(OCHAR, (uch)ch);
1089 cap[ch] = p->g->ncategories++;
1094 - nonnewline - emit REG_NEWLINE version of OANY
1096 * Boy, is this implementation ever a kludge...
1099 nonnewline(struct parse *p)
1101 char *oldnext = p->next;
1102 char *oldend = p->end;
1112 assert(p->next == bracket+3);
1118 - repeat - generate code for a bounded repetition, recursively if needed
1121 repeat(struct parse *p,
1122 sopno start, /* operand from here to end of strip */
1123 int from, /* repeated from this number */
1124 int to) /* to this number of times (maybe INFINITY) */
1126 sopno finish = HERE();
1129 # define REP(f, t) ((f)*8 + (t))
1130 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1133 if (p->error != 0) /* head off possible runaway recursion */
1138 switch (REP(MAP(from), MAP(to))) {
1139 case REP(0, 0): /* must be user doing this */
1140 DROP(finish-start); /* drop the operand */
1142 case REP(0, 1): /* as x{1,1}? */
1143 case REP(0, N): /* as x{1,n}? */
1144 case REP(0, INF): /* as x{1,}? */
1145 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1146 INSERT(OCH_, start); /* offset is wrong... */
1147 repeat(p, start+1, 1, to);
1148 ASTERN(OOR1, start);
1149 AHEAD(start); /* ... fix it */
1152 ASTERN(O_CH, THERETHERE());
1154 case REP(1, 1): /* trivial case */
1157 case REP(1, N): /* as x?x{1,n-1} */
1158 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1159 INSERT(OCH_, start);
1160 ASTERN(OOR1, start);
1162 EMIT(OOR2, 0); /* offset very wrong... */
1163 AHEAD(THERE()); /* ...so fix it */
1164 ASTERN(O_CH, THERETHERE());
1165 copy = dupl(p, start+1, finish+1);
1166 assert(copy == finish+4);
1167 repeat(p, copy, 1, to-1);
1169 case REP(1, INF): /* as x+ */
1170 INSERT(OPLUS_, start);
1171 ASTERN(O_PLUS, start);
1173 case REP(N, N): /* as xx{m-1,n-1} */
1174 copy = dupl(p, start, finish);
1175 repeat(p, copy, from-1, to-1);
1177 case REP(N, INF): /* as xx{n-1,INF} */
1178 copy = dupl(p, start, finish);
1179 repeat(p, copy, from-1, to);
1181 default: /* "can't happen" */
1182 SETERROR(REG_ASSERT); /* just in case */
1188 - seterr - set an error condition
1190 static int /* useless but makes type checking happy */
1191 seterr(struct parse *p, int e)
1193 if (p->error == 0) /* keep earliest error condition */
1195 p->next = nuls; /* try to bring things to a halt */
1197 return(0); /* make the return value well-defined */
1201 - allocset - allocate a set of characters for []
1204 allocset(struct parse *p)
1206 int no = p->g->ncsets++;
1210 size_t css = (size_t)p->g->csetsize;
1213 if (no >= p->ncsalloc) { /* need another column of space */
1216 p->ncsalloc += CHAR_BIT;
1218 if (nc > SIZE_MAX / sizeof(cset))
1220 assert(nc % CHAR_BIT == 0);
1221 nbytes = nc / CHAR_BIT * css;
1223 ptr = (cset *)realloc((char *)p->g->sets, nc * sizeof(cset));
1228 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1231 p->g->setbits = ptr;
1233 for (i = 0; i < no; i++)
1234 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1236 (void) memset((char *)p->g->setbits + (nbytes - css), 0, css);
1238 /* XXX should not happen */
1239 if (p->g->sets == NULL || p->g->setbits == NULL)
1242 cs = &p->g->sets[no];
1243 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1244 cs->mask = 1 << ((no) % CHAR_BIT);
1253 free(p->g->setbits);
1254 p->g->setbits = NULL;
1256 SETERROR(REG_ESPACE);
1257 /* caller's responsibility not to do set ops */
1262 - freeset - free a now-unused set
1265 freeset(struct parse *p, cset *cs)
1268 cset *top = &p->g->sets[p->g->ncsets];
1269 size_t css = (size_t)p->g->csetsize;
1271 for (i = 0; i < css; i++)
1273 if (cs == top-1) /* recover only the easy case */
1278 - freezeset - final processing on a set of characters
1280 * The main task here is merging identical sets. This is usually a waste
1281 * of time (although the hash code minimizes the overhead), but can win
1282 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1283 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1286 static int /* set number */
1287 freezeset(struct parse *p, cset *cs)
1291 cset *top = &p->g->sets[p->g->ncsets];
1293 size_t css = (size_t)p->g->csetsize;
1295 /* look for an earlier one which is the same */
1296 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1297 if (cs2->hash == h && cs2 != cs) {
1299 for (i = 0; i < css; i++)
1300 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1306 if (cs2 < top) { /* found one */
1311 return((int)(cs - p->g->sets));
1315 - firstch - return first character in a set (which must have at least one)
1317 static int /* character; there is no "none" value */
1318 firstch(struct parse *p, cset *cs)
1321 size_t css = (size_t)p->g->csetsize;
1323 for (i = 0; i < css; i++)
1327 return(0); /* arbitrary */
1331 - nch - number of characters in a set
1334 nch(struct parse *p, cset *cs)
1337 size_t css = (size_t)p->g->csetsize;
1340 for (i = 0; i < css; i++)
1347 - mcadd - add a collating element to a cset
1350 mcadd( struct parse *p, cset *cs, const char *cp)
1352 size_t oldend = cs->smultis;
1355 cs->smultis += strlen(cp) + 1;
1356 np = realloc(cs->multis, cs->smultis);
1361 SETERROR(REG_ESPACE);
1366 llvm_strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1370 - mcinvert - invert the list of collating elements in a cset
1372 * This would have to know the set of possibilities. Implementation
1377 mcinvert(struct parse *p, cset *cs)
1379 assert(cs->multis == NULL); /* xxx */
1383 - mccase - add case counterparts of the list of collating elements in a cset
1385 * This would have to know the set of possibilities. Implementation
1390 mccase(struct parse *p, cset *cs)
1392 assert(cs->multis == NULL); /* xxx */
1396 - isinsets - is this character in any sets?
1398 static int /* predicate */
1399 isinsets(struct re_guts *g, int c)
1403 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1404 unsigned uc = (uch)c;
1406 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1413 - samesets - are these two characters in exactly the same sets?
1415 static int /* predicate */
1416 samesets(struct re_guts *g, int c1, int c2)
1420 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1421 unsigned uc1 = (uch)c1;
1422 unsigned uc2 = (uch)c2;
1424 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1425 if (col[uc1] != col[uc2])
1431 - categorize - sort out character categories
1434 categorize(struct parse *p, struct re_guts *g)
1436 cat_t *cats = g->categories;
1441 /* avoid making error situations worse */
1445 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1446 if (cats[c] == 0 && isinsets(g, c)) {
1447 cat = g->ncategories++;
1449 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1450 if (cats[c2] == 0 && samesets(g, c, c2))
1456 - dupl - emit a duplicate of a bunch of sops
1458 static sopno /* start of duplicate */
1459 dupl(struct parse *p,
1460 sopno start, /* from here */
1461 sopno finish) /* to this less one */
1464 sopno len = finish - start;
1466 assert(finish >= start);
1469 enlarge(p, p->ssize + len); /* this many unexpected additions */
1470 assert(p->ssize >= p->slen + len);
1471 (void) memmove((char *)(p->strip + p->slen),
1472 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1478 - doemit - emit a strip operator
1480 * It might seem better to implement this as a macro with a function as
1481 * hard-case backup, but it's just too big and messy unless there are
1482 * some changes to the data structures. Maybe later.
1485 doemit(struct parse *p, sop op, size_t opnd)
1487 /* avoid making error situations worse */
1491 /* deal with oversize operands ("can't happen", more or less) */
1492 assert(opnd < 1<<OPSHIFT);
1494 /* deal with undersized strip */
1495 if (p->slen >= p->ssize)
1496 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1497 assert(p->slen < p->ssize);
1499 /* finally, it's all reduced to the easy case */
1500 p->strip[p->slen++] = SOP(op, opnd);
1504 - doinsert - insert a sop into the strip
1507 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1513 /* avoid making error situations worse */
1518 EMIT(op, opnd); /* do checks, ensure space */
1519 assert(HERE() == sn+1);
1522 /* adjust paren pointers */
1524 for (i = 1; i < NPAREN; i++) {
1525 if (p->pbegin[i] >= pos) {
1528 if (p->pend[i] >= pos) {
1533 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1534 (HERE()-pos-1)*sizeof(sop));
1539 - dofwd - complete a forward reference
1542 dofwd(struct parse *p, sopno pos, sop value)
1544 /* avoid making error situations worse */
1548 assert(value < 1<<OPSHIFT);
1549 p->strip[pos] = OP(p->strip[pos]) | value;
1553 - enlarge - enlarge the strip
1556 enlarge(struct parse *p, sopno size)
1560 if (p->ssize >= size)
1563 if ((uintptr_t)size > SIZE_MAX / sizeof(sop)) {
1564 SETERROR(REG_ESPACE);
1568 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1570 SETERROR(REG_ESPACE);
1578 - stripsnug - compact the strip
1581 stripsnug(struct parse *p, struct re_guts *g)
1583 g->nstates = p->slen;
1584 if ((uintptr_t)p->slen > SIZE_MAX / sizeof(sop)) {
1585 g->strip = p->strip;
1586 SETERROR(REG_ESPACE);
1590 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1591 if (g->strip == NULL) {
1592 SETERROR(REG_ESPACE);
1593 g->strip = p->strip;
1598 - findmust - fill in must and mlen with longest mandatory literal string
1600 * This algorithm could do fancy things like analyzing the operands of |
1601 * for common subsequences. Someday. This code is simple and finds most
1602 * of the interesting cases.
1604 * Note that must and mlen got initialized during setup.
1607 findmust(struct parse *p, struct re_guts *g)
1610 sop *start = 0; /* start initialized in the default case, after that */
1611 sop *newstart = 0; /* newstart was initialized in the OCHAR case */
1617 /* avoid making error situations worse */
1621 /* find the longest OCHAR sequence in strip */
1623 scan = g->strip + 1;
1627 case OCHAR: /* sequence member */
1628 if (newlen == 0) /* new sequence */
1629 newstart = scan - 1;
1632 case OPLUS_: /* things that don't break one */
1636 case OQUEST_: /* things that must be skipped */
1642 /* assert() interferes w debug printouts */
1643 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1645 g->iflags |= REGEX_BAD;
1648 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1650 default: /* things that break a sequence */
1651 if (newlen > g->mlen) { /* ends one */
1658 } while (OP(s) != OEND);
1660 if (g->mlen == 0) /* there isn't one */
1663 /* turn it into a character string */
1664 g->must = malloc((size_t)g->mlen + 1);
1665 if (g->must == NULL) { /* argh; just forget it */
1671 for (i = g->mlen; i > 0; i--) {
1672 while (OP(s = *scan++) != OCHAR)
1674 assert(cp < g->must + g->mlen);
1675 *cp++ = (char)OPND(s);
1677 assert(cp == g->must + g->mlen);
1678 *cp++ = '\0'; /* just on general principles */
1682 - pluscount - count + nesting
1684 static sopno /* nesting depth */
1685 pluscount(struct parse *p, struct re_guts *g)
1693 return(0); /* there may not be an OEND */
1695 scan = g->strip + 1;
1703 if (plusnest > maxnest)
1708 } while (OP(s) != OEND);
1710 g->iflags |= REGEX_BAD;