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 "regcclass.h"
52 #include "llvm/Config/config.h"
56 /* Pessimistically bound memory use */
57 #define SIZE_MAX UINT_MAX
61 * parse structure, passed up and down to avoid global variables and
65 char *next; /* next character in RE */
66 char *end; /* end of string (-> NUL normally) */
67 int error; /* has an error been seen? */
68 sop *strip; /* malloced strip */
69 sopno ssize; /* malloced strip size (allocated) */
70 sopno slen; /* malloced strip length (used) */
71 int ncsalloc; /* number of csets allocated */
73 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
74 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
75 sopno pend[NPAREN]; /* -> ) ([0] unused) */
78 static void p_ere(struct parse *, int);
79 static void p_ere_exp(struct parse *);
80 static void p_str(struct parse *);
81 static void p_bre(struct parse *, int, int);
82 static int p_simp_re(struct parse *, int);
83 static int p_count(struct parse *);
84 static void p_bracket(struct parse *);
85 static void p_b_term(struct parse *, cset *);
86 static void p_b_cclass(struct parse *, cset *);
87 static void p_b_eclass(struct parse *, cset *);
88 static char p_b_symbol(struct parse *);
89 static char p_b_coll_elem(struct parse *, int);
90 static char othercase(int);
91 static void bothcases(struct parse *, int);
92 static void ordinary(struct parse *, int);
93 static void nonnewline(struct parse *);
94 static void repeat(struct parse *, sopno, int, int);
95 static int seterr(struct parse *, int);
96 static cset *allocset(struct parse *);
97 static void freeset(struct parse *, cset *);
98 static int freezeset(struct parse *, cset *);
99 static int firstch(struct parse *, cset *);
100 static int nch(struct parse *, cset *);
101 static void mcadd(struct parse *, cset *, const char *);
102 static void mcinvert(struct parse *, cset *);
103 static void mccase(struct parse *, cset *);
104 static int isinsets(struct re_guts *, int);
105 static int samesets(struct re_guts *, int, int);
106 static void categorize(struct parse *, struct re_guts *);
107 static sopno dupl(struct parse *, sopno, sopno);
108 static void doemit(struct parse *, sop, size_t);
109 static void doinsert(struct parse *, sop, size_t, sopno);
110 static void dofwd(struct parse *, sopno, sop);
111 static void enlarge(struct parse *, sopno);
112 static void stripsnug(struct parse *, struct re_guts *);
113 static void findmust(struct parse *, struct re_guts *);
114 static sopno pluscount(struct parse *, struct re_guts *);
116 static char nuls[10]; /* place to point scanner in event of error */
119 * macros for use with parse structure
120 * BEWARE: these know that the parse structure is named `p' !!!
122 #define PEEK() (*p->next)
123 #define PEEK2() (*(p->next+1))
124 #define MORE() (p->next < p->end)
125 #define MORE2() (p->next+1 < p->end)
126 #define SEE(c) (MORE() && PEEK() == (c))
127 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
128 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
129 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
130 #define NEXT() (p->next++)
131 #define NEXT2() (p->next += 2)
132 #define NEXTn(n) (p->next += (n))
133 #define GETNEXT() (*p->next++)
134 #define SETERROR(e) seterr(p, (e))
135 #define REQUIRE(co, e) (void)((co) || SETERROR(e))
136 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
137 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
138 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
139 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
140 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
141 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
142 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
143 #define HERE() (p->slen)
144 #define THERE() (p->slen - 1)
145 #define THERETHERE() (p->slen - 2)
146 #define DROP(n) (p->slen -= (n))
148 #ifdef _POSIX2_RE_DUP_MAX
149 #define DUPMAX _POSIX2_RE_DUP_MAX
153 #define INFINITY (DUPMAX + 1)
156 static int never = 0; /* for use in asserts; shuts lint up */
158 #define never 0 /* some <assert.h>s have bugs too */
162 - llvm_regcomp - interface for parser and compilation
164 int /* 0 success, otherwise REG_something */
165 llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
169 struct parse *p = &pa;
173 # define GOODFLAGS(f) (f)
175 # define GOODFLAGS(f) ((f)&~REG_DUMP)
178 cflags = GOODFLAGS(cflags);
179 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
182 if (cflags®_PEND) {
183 if (preg->re_endp < pattern)
185 len = preg->re_endp - pattern;
187 len = strlen((const char *)pattern);
189 /* do the mallocs early so failure handling is easy */
190 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
191 (NC-1)*sizeof(cat_t));
194 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
195 p->strip = (sop *)calloc(p->ssize, sizeof(sop));
197 if (p->strip == NULL) {
204 p->next = (char *)pattern; /* convenience; we do not modify it */
205 p->end = p->next + len;
208 for (i = 0; i < NPAREN; i++) {
223 g->ncategories = 1; /* category 0 is "everything else" */
224 g->categories = &g->catspace[-(CHAR_MIN)];
225 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
230 g->firststate = THERE();
231 if (cflags®_EXTENDED)
233 else if (cflags®_NOSPEC)
238 g->laststate = THERE();
240 /* tidy up loose ends and fill things in */
244 g->nplus = pluscount(p, g);
246 preg->re_nsub = g->nsub;
248 preg->re_magic = MAGIC1;
250 /* not debugging, so can't rely on the assert() in llvm_regexec() */
251 if (g->iflags®EX_BAD)
252 SETERROR(REG_ASSERT);
255 /* win or lose, we're done */
256 if (p->error != 0) /* lose */
262 - p_ere - ERE parser top level, concatenation and alternation
265 p_ere(struct parse *p, int stop) /* character this ERE should end at */
271 int first = 1; /* is this the first alternative? */
274 /* do a bunch of concatenated expressions */
276 while (MORE() && (c = PEEK()) != '|' && c != stop)
278 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
281 break; /* NOTE BREAK OUT */
284 INSERT(OCH_, conc); /* offset is wrong */
289 ASTERN(OOR1, prevback);
291 AHEAD(prevfwd); /* fix previous offset */
293 EMIT(OOR2, 0); /* offset is very wrong */
296 if (!first) { /* tail-end fixups */
298 ASTERN(O_CH, prevback);
301 assert(!MORE() || SEE(stop));
305 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
308 p_ere_exp(struct parse *p)
318 assert(MORE()); /* caller should have ensured this */
324 REQUIRE(MORE(), REG_EPAREN);
328 p->pbegin[subno] = HERE();
329 EMIT(OLPAREN, subno);
332 if (subno < NPAREN) {
333 p->pend[subno] = HERE();
334 assert(p->pend[subno] != 0);
336 EMIT(ORPAREN, subno);
337 MUSTEAT(')', REG_EPAREN);
339 #ifndef POSIX_MISTAKE
340 case ')': /* happens only if no current unmatched ( */
342 * You may ask, why the ifndef? Because I didn't notice
343 * this until slightly too late for 1003.2, and none of the
344 * other 1003.2 regular-expression reviewers noticed it at
345 * all. So an unmatched ) is legal POSIX, at least until
346 * we can get it fixed.
348 SETERROR(REG_EPAREN);
353 p->g->iflags |= USEBOL;
359 p->g->iflags |= USEEOL;
368 SETERROR(REG_BADRPT);
371 if (p->g->cflags®_NEWLINE)
380 REQUIRE(MORE(), REG_EESCAPE);
382 if (c >= '1' && c <= '9') {
383 /* \[0-9] is taken to be a back-reference to a previously specified
384 * matching group. backrefnum will hold the number. The matching
385 * group must exist (i.e. if \4 is found there must have been at
386 * least 4 matching groups specified in the pattern previously).
388 backrefnum = c - '0';
389 if (p->pend[backrefnum] == 0) {
390 SETERROR(REG_ESUBREG);
394 /* Make sure everything checks out and emit the sequence
395 * that marks a back-reference to the parse structure.
397 assert(backrefnum <= p->g->nsub);
398 EMIT(OBACK_, backrefnum);
399 assert(p->pbegin[backrefnum] != 0);
400 assert(OP(p->strip[p->pbegin[backrefnum]]) != OLPAREN);
401 assert(OP(p->strip[p->pend[backrefnum]]) != ORPAREN);
402 (void) dupl(p, p->pbegin[backrefnum]+1, p->pend[backrefnum]);
403 EMIT(O_BACK, backrefnum);
406 /* Other chars are simply themselves when escaped with a backslash.
411 case '{': /* okay as ordinary except if digit follows */
412 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
422 /* we call { a repetition if followed by a digit */
423 if (!( c == '*' || c == '+' || c == '?' ||
424 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
425 return; /* no repetition, we're done */
428 REQUIRE(!wascaret, REG_BADRPT);
430 case '*': /* implemented as +? */
431 /* this case does not require the (y|) trick, noKLUDGE */
434 INSERT(OQUEST_, pos);
435 ASTERN(O_QUEST, pos);
442 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
443 INSERT(OCH_, pos); /* offset slightly wrong */
444 ASTERN(OOR1, pos); /* this one's right */
445 AHEAD(pos); /* fix the OCH_ */
446 EMIT(OOR2, 0); /* offset very wrong... */
447 AHEAD(THERE()); /* ...so fix it */
448 ASTERN(O_CH, THERETHERE());
453 if (isdigit((uch)PEEK())) {
455 REQUIRE(count <= count2, REG_BADBR);
456 } else /* single number with comma */
458 } else /* just a single number */
460 repeat(p, pos, count, count2);
461 if (!EAT('}')) { /* error heuristics */
462 while (MORE() && PEEK() != '}')
464 REQUIRE(MORE(), REG_EBRACE);
473 if (!( c == '*' || c == '+' || c == '?' ||
474 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
476 SETERROR(REG_BADRPT);
480 - p_str - string (no metacharacters) "parser"
483 p_str(struct parse *p)
485 REQUIRE(MORE(), REG_EMPTY);
487 ordinary(p, GETNEXT());
491 - p_bre - BRE parser top level, anchoring and concatenation
492 * Giving end1 as OUT essentially eliminates the end1/end2 check.
494 * This implementation is a bit of a kludge, in that a trailing $ is first
495 * taken as an ordinary character and then revised to be an anchor. The
496 * only undesirable side effect is that '$' gets included as a character
497 * category in such cases. This is fairly harmless; not worth fixing.
498 * The amount of lookahead needed to avoid this kludge is excessive.
501 p_bre(struct parse *p,
502 int end1, /* first terminating character */
503 int end2) /* second terminating character */
505 sopno start = HERE();
506 int first = 1; /* first subexpression? */
511 p->g->iflags |= USEBOL;
514 while (MORE() && !SEETWO(end1, end2)) {
515 wasdollar = p_simp_re(p, first);
518 if (wasdollar) { /* oops, that was a trailing anchor */
521 p->g->iflags |= USEEOL;
525 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
529 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
531 static int /* was the simple RE an unbackslashed $? */
532 p_simp_re(struct parse *p,
533 int starordinary) /* is a leading * an ordinary character? */
541 # define BACKSL (1<<CHAR_BIT)
543 pos = HERE(); /* repetition op, if any, covers from here */
545 assert(MORE()); /* caller should have ensured this */
548 REQUIRE(MORE(), REG_EESCAPE);
549 c = BACKSL | GETNEXT();
553 if (p->g->cflags®_NEWLINE)
562 SETERROR(REG_BADRPT);
568 p->pbegin[subno] = HERE();
569 EMIT(OLPAREN, subno);
570 /* the MORE here is an error heuristic */
571 if (MORE() && !SEETWO('\\', ')'))
573 if (subno < NPAREN) {
574 p->pend[subno] = HERE();
575 assert(p->pend[subno] != 0);
577 EMIT(ORPAREN, subno);
578 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
580 case BACKSL|')': /* should not get here -- must be user */
582 SETERROR(REG_EPAREN);
593 i = (c&~BACKSL) - '0';
595 if (p->pend[i] != 0) {
596 assert(i <= p->g->nsub);
598 assert(p->pbegin[i] != 0);
599 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
600 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
601 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
604 SETERROR(REG_ESUBREG);
608 REQUIRE(starordinary, REG_BADRPT);
611 ordinary(p, (char)c);
615 if (EAT('*')) { /* implemented as +? */
616 /* this case does not require the (y|) trick, noKLUDGE */
619 INSERT(OQUEST_, pos);
620 ASTERN(O_QUEST, pos);
621 } else if (EATTWO('\\', '{')) {
624 if (MORE() && isdigit((uch)PEEK())) {
626 REQUIRE(count <= count2, REG_BADBR);
627 } else /* single number with comma */
629 } else /* just a single number */
631 repeat(p, pos, count, count2);
632 if (!EATTWO('\\', '}')) { /* error heuristics */
633 while (MORE() && !SEETWO('\\', '}'))
635 REQUIRE(MORE(), REG_EBRACE);
638 } else if (c == '$') /* $ (but not \$) ends it */
645 - p_count - parse a repetition count
647 static int /* the value */
648 p_count(struct parse *p)
653 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
654 count = count*10 + (GETNEXT() - '0');
658 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
663 - p_bracket - parse a bracketed character list
665 * Note a significant property of this code: if the allocset() did SETERROR,
666 * no set operations are done.
669 p_bracket(struct parse *p)
674 /* Dept of Truly Sickening Special-Case Kludges */
675 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
680 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
686 if ((cs = allocset(p)) == NULL) {
687 /* allocset did set error status in p */
692 invert++; /* make note to invert set at end */
697 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
701 MUSTEAT(']', REG_EBRACK);
703 if (p->error != 0) { /* don't mess things up further */
708 if (p->g->cflags®_ICASE) {
712 for (i = p->g->csetsize - 1; i >= 0; i--)
713 if (CHIN(cs, i) && isalpha(i)) {
718 if (cs->multis != NULL)
724 for (i = p->g->csetsize - 1; i >= 0; i--)
729 if (p->g->cflags®_NEWLINE)
731 if (cs->multis != NULL)
735 assert(cs->multis == NULL); /* xxx */
737 if (nch(p, cs) == 1) { /* optimize singleton sets */
738 ordinary(p, firstch(p, cs));
741 EMIT(OANYOF, freezeset(p, cs));
745 - p_b_term - parse one term of a bracketed character list
748 p_b_term(struct parse *p, cset *cs)
754 /* classify what we've got */
755 switch ((MORE()) ? PEEK() : '\0') {
757 c = (MORE2()) ? PEEK2() : '\0';
760 SETERROR(REG_ERANGE);
761 return; /* NOTE RETURN */
769 case ':': /* character class */
771 REQUIRE(MORE(), REG_EBRACK);
773 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
775 REQUIRE(MORE(), REG_EBRACK);
776 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
778 case '=': /* equivalence class */
780 REQUIRE(MORE(), REG_EBRACK);
782 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
784 REQUIRE(MORE(), REG_EBRACK);
785 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
787 default: /* symbol, ordinary character, or range */
788 /* xxx revision needed for multichar stuff */
789 start = p_b_symbol(p);
790 if (SEE('-') && MORE2() && PEEK2() != ']') {
796 finish = p_b_symbol(p);
799 /* xxx what about signed chars here... */
800 REQUIRE(start <= finish, REG_ERANGE);
801 for (i = start; i <= finish; i++)
808 - p_b_cclass - parse a character-class name and deal with it
811 p_b_cclass(struct parse *p, cset *cs)
819 while (MORE() && isalpha((uch)PEEK()))
822 for (cp = cclasses; cp->name != NULL; cp++)
823 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
825 if (cp->name == NULL) {
826 /* oops, didn't find it */
827 SETERROR(REG_ECTYPE);
832 while ((c = *u++) != '\0')
834 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
839 - p_b_eclass - parse an equivalence-class name and deal with it
841 * This implementation is incomplete. xxx
844 p_b_eclass(struct parse *p, cset *cs)
848 c = p_b_coll_elem(p, '=');
853 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
855 static char /* value of symbol */
856 p_b_symbol(struct parse *p)
860 REQUIRE(MORE(), REG_EBRACK);
861 if (!EATTWO('[', '.'))
864 /* collating symbol */
865 value = p_b_coll_elem(p, '.');
866 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
871 - p_b_coll_elem - parse a collating-element name and look it up
873 static char /* value of collating element */
874 p_b_coll_elem(struct parse *p,
875 int endc) /* name ended by endc,']' */
881 while (MORE() && !SEETWO(endc, ']'))
884 SETERROR(REG_EBRACK);
888 for (cp = cnames; cp->name != NULL; cp++)
889 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
890 return(cp->code); /* known name */
892 return(*sp); /* single character */
893 SETERROR(REG_ECOLLATE); /* neither */
898 - othercase - return the case counterpart of an alphabetic
900 static char /* if no counterpart, return ch */
906 return ((uch)tolower(ch));
907 else if (islower(ch))
908 return ((uch)toupper(ch));
909 else /* peculiar, but could happen */
914 - bothcases - emit a dualcase version of a two-case character
916 * Boy, is this implementation ever a kludge...
919 bothcases(struct parse *p, int ch)
921 char *oldnext = p->next;
922 char *oldend = p->end;
926 assert(othercase(ch) != ch); /* p_bracket() would recurse */
933 assert(p->next == bracket+2);
939 - ordinary - emit an ordinary character
942 ordinary(struct parse *p, int ch)
944 cat_t *cap = p->g->categories;
946 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
949 EMIT(OCHAR, (uch)ch);
951 cap[ch] = p->g->ncategories++;
956 - nonnewline - emit REG_NEWLINE version of OANY
958 * Boy, is this implementation ever a kludge...
961 nonnewline(struct parse *p)
963 char *oldnext = p->next;
964 char *oldend = p->end;
974 assert(p->next == bracket+3);
980 - repeat - generate code for a bounded repetition, recursively if needed
983 repeat(struct parse *p,
984 sopno start, /* operand from here to end of strip */
985 int from, /* repeated from this number */
986 int to) /* to this number of times (maybe INFINITY) */
988 sopno finish = HERE();
991 # define REP(f, t) ((f)*8 + (t))
992 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
995 if (p->error != 0) /* head off possible runaway recursion */
1000 switch (REP(MAP(from), MAP(to))) {
1001 case REP(0, 0): /* must be user doing this */
1002 DROP(finish-start); /* drop the operand */
1004 case REP(0, 1): /* as x{1,1}? */
1005 case REP(0, N): /* as x{1,n}? */
1006 case REP(0, INF): /* as x{1,}? */
1007 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1008 INSERT(OCH_, start); /* offset is wrong... */
1009 repeat(p, start+1, 1, to);
1010 ASTERN(OOR1, start);
1011 AHEAD(start); /* ... fix it */
1014 ASTERN(O_CH, THERETHERE());
1016 case REP(1, 1): /* trivial case */
1019 case REP(1, N): /* as x?x{1,n-1} */
1020 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1021 INSERT(OCH_, start);
1022 ASTERN(OOR1, start);
1024 EMIT(OOR2, 0); /* offset very wrong... */
1025 AHEAD(THERE()); /* ...so fix it */
1026 ASTERN(O_CH, THERETHERE());
1027 copy = dupl(p, start+1, finish+1);
1028 assert(copy == finish+4);
1029 repeat(p, copy, 1, to-1);
1031 case REP(1, INF): /* as x+ */
1032 INSERT(OPLUS_, start);
1033 ASTERN(O_PLUS, start);
1035 case REP(N, N): /* as xx{m-1,n-1} */
1036 copy = dupl(p, start, finish);
1037 repeat(p, copy, from-1, to-1);
1039 case REP(N, INF): /* as xx{n-1,INF} */
1040 copy = dupl(p, start, finish);
1041 repeat(p, copy, from-1, to);
1043 default: /* "can't happen" */
1044 SETERROR(REG_ASSERT); /* just in case */
1050 - seterr - set an error condition
1052 static int /* useless but makes type checking happy */
1053 seterr(struct parse *p, int e)
1055 if (p->error == 0) /* keep earliest error condition */
1057 p->next = nuls; /* try to bring things to a halt */
1059 return(0); /* make the return value well-defined */
1063 - allocset - allocate a set of characters for []
1066 allocset(struct parse *p)
1068 int no = p->g->ncsets++;
1072 size_t css = (size_t)p->g->csetsize;
1075 if (no >= p->ncsalloc) { /* need another column of space */
1078 p->ncsalloc += CHAR_BIT;
1080 if (nc > SIZE_MAX / sizeof(cset))
1082 assert(nc % CHAR_BIT == 0);
1083 nbytes = nc / CHAR_BIT * css;
1085 ptr = (cset *)realloc((char *)p->g->sets, nc * sizeof(cset));
1090 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1093 p->g->setbits = ptr;
1095 for (i = 0; i < no; i++)
1096 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1098 (void) memset((char *)p->g->setbits + (nbytes - css), 0, css);
1100 /* XXX should not happen */
1101 if (p->g->sets == NULL || p->g->setbits == NULL)
1104 cs = &p->g->sets[no];
1105 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1106 cs->mask = 1 << ((no) % CHAR_BIT);
1115 free(p->g->setbits);
1116 p->g->setbits = NULL;
1118 SETERROR(REG_ESPACE);
1119 /* caller's responsibility not to do set ops */
1124 - freeset - free a now-unused set
1127 freeset(struct parse *p, cset *cs)
1130 cset *top = &p->g->sets[p->g->ncsets];
1131 size_t css = (size_t)p->g->csetsize;
1133 for (i = 0; i < css; i++)
1135 if (cs == top-1) /* recover only the easy case */
1140 - freezeset - final processing on a set of characters
1142 * The main task here is merging identical sets. This is usually a waste
1143 * of time (although the hash code minimizes the overhead), but can win
1144 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1145 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1148 static int /* set number */
1149 freezeset(struct parse *p, cset *cs)
1153 cset *top = &p->g->sets[p->g->ncsets];
1155 size_t css = (size_t)p->g->csetsize;
1157 /* look for an earlier one which is the same */
1158 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1159 if (cs2->hash == h && cs2 != cs) {
1161 for (i = 0; i < css; i++)
1162 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1168 if (cs2 < top) { /* found one */
1173 return((int)(cs - p->g->sets));
1177 - firstch - return first character in a set (which must have at least one)
1179 static int /* character; there is no "none" value */
1180 firstch(struct parse *p, cset *cs)
1183 size_t css = (size_t)p->g->csetsize;
1185 for (i = 0; i < css; i++)
1189 return(0); /* arbitrary */
1193 - nch - number of characters in a set
1196 nch(struct parse *p, cset *cs)
1199 size_t css = (size_t)p->g->csetsize;
1202 for (i = 0; i < css; i++)
1209 - mcadd - add a collating element to a cset
1212 mcadd( struct parse *p, cset *cs, const char *cp)
1214 size_t oldend = cs->smultis;
1217 cs->smultis += strlen(cp) + 1;
1218 np = realloc(cs->multis, cs->smultis);
1223 SETERROR(REG_ESPACE);
1228 llvm_strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1232 - mcinvert - invert the list of collating elements in a cset
1234 * This would have to know the set of possibilities. Implementation
1239 mcinvert(struct parse *p, cset *cs)
1241 assert(cs->multis == NULL); /* xxx */
1245 - mccase - add case counterparts of the list of collating elements in a cset
1247 * This would have to know the set of possibilities. Implementation
1252 mccase(struct parse *p, cset *cs)
1254 assert(cs->multis == NULL); /* xxx */
1258 - isinsets - is this character in any sets?
1260 static int /* predicate */
1261 isinsets(struct re_guts *g, int c)
1265 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1266 unsigned uc = (uch)c;
1268 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1275 - samesets - are these two characters in exactly the same sets?
1277 static int /* predicate */
1278 samesets(struct re_guts *g, int c1, int c2)
1282 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1283 unsigned uc1 = (uch)c1;
1284 unsigned uc2 = (uch)c2;
1286 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1287 if (col[uc1] != col[uc2])
1293 - categorize - sort out character categories
1296 categorize(struct parse *p, struct re_guts *g)
1298 cat_t *cats = g->categories;
1303 /* avoid making error situations worse */
1307 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1308 if (cats[c] == 0 && isinsets(g, c)) {
1309 cat = g->ncategories++;
1311 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1312 if (cats[c2] == 0 && samesets(g, c, c2))
1318 - dupl - emit a duplicate of a bunch of sops
1320 static sopno /* start of duplicate */
1321 dupl(struct parse *p,
1322 sopno start, /* from here */
1323 sopno finish) /* to this less one */
1326 sopno len = finish - start;
1328 assert(finish >= start);
1331 enlarge(p, p->ssize + len); /* this many unexpected additions */
1332 assert(p->ssize >= p->slen + len);
1333 (void) memmove((char *)(p->strip + p->slen),
1334 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1340 - doemit - emit a strip operator
1342 * It might seem better to implement this as a macro with a function as
1343 * hard-case backup, but it's just too big and messy unless there are
1344 * some changes to the data structures. Maybe later.
1347 doemit(struct parse *p, sop op, size_t opnd)
1349 /* avoid making error situations worse */
1353 /* deal with oversize operands ("can't happen", more or less) */
1354 assert(opnd < 1<<OPSHIFT);
1356 /* deal with undersized strip */
1357 if (p->slen >= p->ssize)
1358 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1359 assert(p->slen < p->ssize);
1361 /* finally, it's all reduced to the easy case */
1362 p->strip[p->slen++] = SOP(op, opnd);
1366 - doinsert - insert a sop into the strip
1369 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1375 /* avoid making error situations worse */
1380 EMIT(op, opnd); /* do checks, ensure space */
1381 assert(HERE() == sn+1);
1384 /* adjust paren pointers */
1386 for (i = 1; i < NPAREN; i++) {
1387 if (p->pbegin[i] >= pos) {
1390 if (p->pend[i] >= pos) {
1395 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1396 (HERE()-pos-1)*sizeof(sop));
1401 - dofwd - complete a forward reference
1404 dofwd(struct parse *p, sopno pos, sop value)
1406 /* avoid making error situations worse */
1410 assert(value < 1<<OPSHIFT);
1411 p->strip[pos] = OP(p->strip[pos]) | value;
1415 - enlarge - enlarge the strip
1418 enlarge(struct parse *p, sopno size)
1422 if (p->ssize >= size)
1425 if ((uintptr_t)size > SIZE_MAX / sizeof(sop)) {
1426 SETERROR(REG_ESPACE);
1430 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1432 SETERROR(REG_ESPACE);
1440 - stripsnug - compact the strip
1443 stripsnug(struct parse *p, struct re_guts *g)
1445 g->nstates = p->slen;
1446 if ((uintptr_t)p->slen > SIZE_MAX / sizeof(sop)) {
1447 g->strip = p->strip;
1448 SETERROR(REG_ESPACE);
1452 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1453 if (g->strip == NULL) {
1454 SETERROR(REG_ESPACE);
1455 g->strip = p->strip;
1460 - findmust - fill in must and mlen with longest mandatory literal string
1462 * This algorithm could do fancy things like analyzing the operands of |
1463 * for common subsequences. Someday. This code is simple and finds most
1464 * of the interesting cases.
1466 * Note that must and mlen got initialized during setup.
1469 findmust(struct parse *p, struct re_guts *g)
1472 sop *start = 0; /* start initialized in the default case, after that */
1473 sop *newstart = 0; /* newstart was initialized in the OCHAR case */
1479 /* avoid making error situations worse */
1483 /* find the longest OCHAR sequence in strip */
1485 scan = g->strip + 1;
1489 case OCHAR: /* sequence member */
1490 if (newlen == 0) /* new sequence */
1491 newstart = scan - 1;
1494 case OPLUS_: /* things that don't break one */
1498 case OQUEST_: /* things that must be skipped */
1504 /* assert() interferes w debug printouts */
1505 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1507 g->iflags |= REGEX_BAD;
1510 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1512 default: /* things that break a sequence */
1513 if (newlen > g->mlen) { /* ends one */
1520 } while (OP(s) != OEND);
1522 if (g->mlen == 0) /* there isn't one */
1525 /* turn it into a character string */
1526 g->must = malloc((size_t)g->mlen + 1);
1527 if (g->must == NULL) { /* argh; just forget it */
1533 for (i = g->mlen; i > 0; i--) {
1534 while (OP(s = *scan++) != OCHAR)
1536 assert(cp < g->must + g->mlen);
1537 *cp++ = (char)OPND(s);
1539 assert(cp == g->must + g->mlen);
1540 *cp++ = '\0'; /* just on general principles */
1544 - pluscount - count + nesting
1546 static sopno /* nesting depth */
1547 pluscount(struct parse *p, struct re_guts *g)
1555 return(0); /* there may not be an OEND */
1557 scan = g->strip + 1;
1565 if (plusnest > maxnest)
1570 } while (OP(s) != OEND);
1572 g->iflags |= REGEX_BAD;