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"
53 * parse structure, passed up and down to avoid global variables and
57 char *next; /* next character in RE */
58 char *end; /* end of string (-> NUL normally) */
59 int error; /* has an error been seen? */
60 sop *strip; /* malloced strip */
61 sopno ssize; /* malloced strip size (allocated) */
62 sopno slen; /* malloced strip length (used) */
63 int ncsalloc; /* number of csets allocated */
65 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
66 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
67 sopno pend[NPAREN]; /* -> ) ([0] unused) */
70 static void p_ere(struct parse *, int);
71 static void p_ere_exp(struct parse *);
72 static void p_str(struct parse *);
73 static void p_bre(struct parse *, int, int);
74 static int p_simp_re(struct parse *, int);
75 static int p_count(struct parse *);
76 static void p_bracket(struct parse *);
77 static void p_b_term(struct parse *, cset *);
78 static void p_b_cclass(struct parse *, cset *);
79 static void p_b_eclass(struct parse *, cset *);
80 static char p_b_symbol(struct parse *);
81 static char p_b_coll_elem(struct parse *, int);
82 static char othercase(int);
83 static void bothcases(struct parse *, int);
84 static void ordinary(struct parse *, int);
85 static void nonnewline(struct parse *);
86 static void repeat(struct parse *, sopno, int, int);
87 static int seterr(struct parse *, int);
88 static cset *allocset(struct parse *);
89 static void freeset(struct parse *, cset *);
90 static int freezeset(struct parse *, cset *);
91 static int firstch(struct parse *, cset *);
92 static int nch(struct parse *, cset *);
93 static void mcadd(struct parse *, cset *, const char *);
94 static void mcinvert(struct parse *, cset *);
95 static void mccase(struct parse *, cset *);
96 static int isinsets(struct re_guts *, int);
97 static int samesets(struct re_guts *, int, int);
98 static void categorize(struct parse *, struct re_guts *);
99 static sopno dupl(struct parse *, sopno, sopno);
100 static void doemit(struct parse *, sop, size_t);
101 static void doinsert(struct parse *, sop, size_t, sopno);
102 static void dofwd(struct parse *, sopno, sop);
103 static void enlarge(struct parse *, sopno);
104 static void stripsnug(struct parse *, struct re_guts *);
105 static void findmust(struct parse *, struct re_guts *);
106 static sopno pluscount(struct parse *, struct re_guts *);
108 static char nuls[10]; /* place to point scanner in event of error */
111 * macros for use with parse structure
112 * BEWARE: these know that the parse structure is named `p' !!!
114 #define PEEK() (*p->next)
115 #define PEEK2() (*(p->next+1))
116 #define MORE() (p->next < p->end)
117 #define MORE2() (p->next+1 < p->end)
118 #define SEE(c) (MORE() && PEEK() == (c))
119 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
120 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
121 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
122 #define NEXT() (p->next++)
123 #define NEXT2() (p->next += 2)
124 #define NEXTn(n) (p->next += (n))
125 #define GETNEXT() (*p->next++)
126 #define SETERROR(e) seterr(p, (e))
127 #define REQUIRE(co, e) (void)((co) || SETERROR(e))
128 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
129 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
130 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
131 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
132 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
133 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
134 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
135 #define HERE() (p->slen)
136 #define THERE() (p->slen - 1)
137 #define THERETHERE() (p->slen - 2)
138 #define DROP(n) (p->slen -= (n))
140 #ifdef _POSIX2_RE_DUP_MAX
141 #define DUPMAX _POSIX2_RE_DUP_MAX
147 static int never = 0; /* for use in asserts; shuts lint up */
149 #define never 0 /* some <assert.h>s have bugs too */
153 - llvm_regcomp - interface for parser and compilation
155 int /* 0 success, otherwise REG_something */
156 llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
160 struct parse *p = &pa;
164 # define GOODFLAGS(f) (f)
166 # define GOODFLAGS(f) ((f)&~REG_DUMP)
169 cflags = GOODFLAGS(cflags);
170 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
173 if (cflags®_PEND) {
174 if (preg->re_endp < pattern)
176 len = preg->re_endp - pattern;
178 len = strlen((const char *)pattern);
180 /* do the mallocs early so failure handling is easy */
181 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
182 (NC-1)*sizeof(cat_t));
185 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
186 p->strip = (sop *)calloc(p->ssize, sizeof(sop));
188 if (p->strip == NULL) {
195 p->next = (char *)pattern; /* convenience; we do not modify it */
196 p->end = p->next + len;
199 for (i = 0; i < NPAREN; i++) {
214 g->ncategories = 1; /* category 0 is "everything else" */
215 g->categories = &g->catspace[-(CHAR_MIN)];
216 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
221 g->firststate = THERE();
222 if (cflags®_EXTENDED)
224 else if (cflags®_NOSPEC)
229 g->laststate = THERE();
231 /* tidy up loose ends and fill things in */
235 g->nplus = pluscount(p, g);
237 preg->re_nsub = g->nsub;
239 preg->re_magic = MAGIC1;
241 /* not debugging, so can't rely on the assert() in llvm_regexec() */
242 if (g->iflags®EX_BAD)
243 SETERROR(REG_ASSERT);
246 /* win or lose, we're done */
247 if (p->error != 0) /* lose */
253 - p_ere - ERE parser top level, concatenation and alternation
256 p_ere(struct parse *p, int stop) /* character this ERE should end at */
262 int first = 1; /* is this the first alternative? */
265 /* do a bunch of concatenated expressions */
267 while (MORE() && (c = PEEK()) != '|' && c != stop)
269 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
272 break; /* NOTE BREAK OUT */
275 INSERT(OCH_, conc); /* offset is wrong */
280 ASTERN(OOR1, prevback);
282 AHEAD(prevfwd); /* fix previous offset */
284 EMIT(OOR2, 0); /* offset is very wrong */
287 if (!first) { /* tail-end fixups */
289 ASTERN(O_CH, prevback);
292 assert(!MORE() || SEE(stop));
296 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
299 p_ere_exp(struct parse *p)
308 assert(MORE()); /* caller should have ensured this */
314 REQUIRE(MORE(), REG_EPAREN);
318 p->pbegin[subno] = HERE();
319 EMIT(OLPAREN, subno);
322 if (subno < NPAREN) {
323 p->pend[subno] = HERE();
324 assert(p->pend[subno] != 0);
326 EMIT(ORPAREN, subno);
327 MUSTEAT(')', REG_EPAREN);
329 #ifndef POSIX_MISTAKE
330 case ')': /* happens only if no current unmatched ( */
332 * You may ask, why the ifndef? Because I didn't notice
333 * this until slightly too late for 1003.2, and none of the
334 * other 1003.2 regular-expression reviewers noticed it at
335 * all. So an unmatched ) is legal POSIX, at least until
336 * we can get it fixed.
338 SETERROR(REG_EPAREN);
343 p->g->iflags |= USEBOL;
349 p->g->iflags |= USEEOL;
358 SETERROR(REG_BADRPT);
361 if (p->g->cflags®_NEWLINE)
370 REQUIRE(MORE(), REG_EESCAPE);
374 case '{': /* okay as ordinary except if digit follows */
375 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
385 /* we call { a repetition if followed by a digit */
386 if (!( c == '*' || c == '+' || c == '?' ||
387 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
388 return; /* no repetition, we're done */
391 REQUIRE(!wascaret, REG_BADRPT);
393 case '*': /* implemented as +? */
394 /* this case does not require the (y|) trick, noKLUDGE */
397 INSERT(OQUEST_, pos);
398 ASTERN(O_QUEST, pos);
405 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
406 INSERT(OCH_, pos); /* offset slightly wrong */
407 ASTERN(OOR1, pos); /* this one's right */
408 AHEAD(pos); /* fix the OCH_ */
409 EMIT(OOR2, 0); /* offset very wrong... */
410 AHEAD(THERE()); /* ...so fix it */
411 ASTERN(O_CH, THERETHERE());
416 if (isdigit((uch)PEEK())) {
418 REQUIRE(count <= count2, REG_BADBR);
419 } else /* single number with comma */
421 } else /* just a single number */
423 repeat(p, pos, count, count2);
424 if (!EAT('}')) { /* error heuristics */
425 while (MORE() && PEEK() != '}')
427 REQUIRE(MORE(), REG_EBRACE);
436 if (!( c == '*' || c == '+' || c == '?' ||
437 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
439 SETERROR(REG_BADRPT);
443 - p_str - string (no metacharacters) "parser"
446 p_str(struct parse *p)
448 REQUIRE(MORE(), REG_EMPTY);
450 ordinary(p, GETNEXT());
454 - p_bre - BRE parser top level, anchoring and concatenation
455 * Giving end1 as OUT essentially eliminates the end1/end2 check.
457 * This implementation is a bit of a kludge, in that a trailing $ is first
458 * taken as an ordinary character and then revised to be an anchor. The
459 * only undesirable side effect is that '$' gets included as a character
460 * category in such cases. This is fairly harmless; not worth fixing.
461 * The amount of lookahead needed to avoid this kludge is excessive.
464 p_bre(struct parse *p,
465 int end1, /* first terminating character */
466 int end2) /* second terminating character */
468 sopno start = HERE();
469 int first = 1; /* first subexpression? */
474 p->g->iflags |= USEBOL;
477 while (MORE() && !SEETWO(end1, end2)) {
478 wasdollar = p_simp_re(p, first);
481 if (wasdollar) { /* oops, that was a trailing anchor */
484 p->g->iflags |= USEEOL;
488 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
492 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
494 static int /* was the simple RE an unbackslashed $? */
495 p_simp_re(struct parse *p,
496 int starordinary) /* is a leading * an ordinary character? */
504 # define BACKSL (1<<CHAR_BIT)
506 pos = HERE(); /* repetion op, if any, covers from here */
508 assert(MORE()); /* caller should have ensured this */
511 REQUIRE(MORE(), REG_EESCAPE);
512 c = BACKSL | GETNEXT();
516 if (p->g->cflags®_NEWLINE)
525 SETERROR(REG_BADRPT);
531 p->pbegin[subno] = HERE();
532 EMIT(OLPAREN, subno);
533 /* the MORE here is an error heuristic */
534 if (MORE() && !SEETWO('\\', ')'))
536 if (subno < NPAREN) {
537 p->pend[subno] = HERE();
538 assert(p->pend[subno] != 0);
540 EMIT(ORPAREN, subno);
541 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
543 case BACKSL|')': /* should not get here -- must be user */
545 SETERROR(REG_EPAREN);
556 i = (c&~BACKSL) - '0';
558 if (p->pend[i] != 0) {
559 assert(i <= p->g->nsub);
561 assert(p->pbegin[i] != 0);
562 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
563 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
564 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
567 SETERROR(REG_ESUBREG);
571 REQUIRE(starordinary, REG_BADRPT);
574 ordinary(p, (char)c);
578 if (EAT('*')) { /* implemented as +? */
579 /* this case does not require the (y|) trick, noKLUDGE */
582 INSERT(OQUEST_, pos);
583 ASTERN(O_QUEST, pos);
584 } else if (EATTWO('\\', '{')) {
587 if (MORE() && isdigit((uch)PEEK())) {
589 REQUIRE(count <= count2, REG_BADBR);
590 } else /* single number with comma */
592 } else /* just a single number */
594 repeat(p, pos, count, count2);
595 if (!EATTWO('\\', '}')) { /* error heuristics */
596 while (MORE() && !SEETWO('\\', '}'))
598 REQUIRE(MORE(), REG_EBRACE);
601 } else if (c == '$') /* $ (but not \$) ends it */
608 - p_count - parse a repetition count
610 static int /* the value */
611 p_count(struct parse *p)
616 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
617 count = count*10 + (GETNEXT() - '0');
621 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
626 - p_bracket - parse a bracketed character list
628 * Note a significant property of this code: if the allocset() did SETERROR,
629 * no set operations are done.
632 p_bracket(struct parse *p)
637 /* Dept of Truly Sickening Special-Case Kludges */
638 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
643 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
649 if ((cs = allocset(p)) == NULL) {
650 /* allocset did set error status in p */
655 invert++; /* make note to invert set at end */
660 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
664 MUSTEAT(']', REG_EBRACK);
666 if (p->error != 0) { /* don't mess things up further */
671 if (p->g->cflags®_ICASE) {
675 for (i = p->g->csetsize - 1; i >= 0; i--)
676 if (CHIN(cs, i) && isalpha(i)) {
681 if (cs->multis != NULL)
687 for (i = p->g->csetsize - 1; i >= 0; i--)
692 if (p->g->cflags®_NEWLINE)
694 if (cs->multis != NULL)
698 assert(cs->multis == NULL); /* xxx */
700 if (nch(p, cs) == 1) { /* optimize singleton sets */
701 ordinary(p, firstch(p, cs));
704 EMIT(OANYOF, freezeset(p, cs));
708 - p_b_term - parse one term of a bracketed character list
711 p_b_term(struct parse *p, cset *cs)
717 /* classify what we've got */
718 switch ((MORE()) ? PEEK() : '\0') {
720 c = (MORE2()) ? PEEK2() : '\0';
723 SETERROR(REG_ERANGE);
724 return; /* NOTE RETURN */
732 case ':': /* character class */
734 REQUIRE(MORE(), REG_EBRACK);
736 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
738 REQUIRE(MORE(), REG_EBRACK);
739 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
741 case '=': /* equivalence class */
743 REQUIRE(MORE(), REG_EBRACK);
745 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
747 REQUIRE(MORE(), REG_EBRACK);
748 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
750 default: /* symbol, ordinary character, or range */
751 /* xxx revision needed for multichar stuff */
752 start = p_b_symbol(p);
753 if (SEE('-') && MORE2() && PEEK2() != ']') {
759 finish = p_b_symbol(p);
762 /* xxx what about signed chars here... */
763 REQUIRE(start <= finish, REG_ERANGE);
764 for (i = start; i <= finish; i++)
771 - p_b_cclass - parse a character-class name and deal with it
774 p_b_cclass(struct parse *p, cset *cs)
782 while (MORE() && isalpha(PEEK()))
785 for (cp = cclasses; cp->name != NULL; cp++)
786 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
788 if (cp->name == NULL) {
789 /* oops, didn't find it */
790 SETERROR(REG_ECTYPE);
795 while ((c = *u++) != '\0')
797 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
802 - p_b_eclass - parse an equivalence-class name and deal with it
804 * This implementation is incomplete. xxx
807 p_b_eclass(struct parse *p, cset *cs)
811 c = p_b_coll_elem(p, '=');
816 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
818 static char /* value of symbol */
819 p_b_symbol(struct parse *p)
823 REQUIRE(MORE(), REG_EBRACK);
824 if (!EATTWO('[', '.'))
827 /* collating symbol */
828 value = p_b_coll_elem(p, '.');
829 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
834 - p_b_coll_elem - parse a collating-element name and look it up
836 static char /* value of collating element */
837 p_b_coll_elem(struct parse *p,
838 int endc) /* name ended by endc,']' */
844 while (MORE() && !SEETWO(endc, ']'))
847 SETERROR(REG_EBRACK);
851 for (cp = cnames; cp->name != NULL; cp++)
852 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
853 return(cp->code); /* known name */
855 return(*sp); /* single character */
856 SETERROR(REG_ECOLLATE); /* neither */
861 - othercase - return the case counterpart of an alphabetic
863 static char /* if no counterpart, return ch */
869 return ((uch)tolower(ch));
870 else if (islower(ch))
871 return ((uch)toupper(ch));
872 else /* peculiar, but could happen */
877 - bothcases - emit a dualcase version of a two-case character
879 * Boy, is this implementation ever a kludge...
882 bothcases(struct parse *p, int ch)
884 char *oldnext = p->next;
885 char *oldend = p->end;
889 assert(othercase(ch) != ch); /* p_bracket() would recurse */
896 assert(p->next == bracket+2);
902 - ordinary - emit an ordinary character
905 ordinary(struct parse *p, int ch)
907 cat_t *cap = p->g->categories;
909 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
912 EMIT(OCHAR, (uch)ch);
914 cap[ch] = p->g->ncategories++;
919 - nonnewline - emit REG_NEWLINE version of OANY
921 * Boy, is this implementation ever a kludge...
924 nonnewline(struct parse *p)
926 char *oldnext = p->next;
927 char *oldend = p->end;
937 assert(p->next == bracket+3);
943 - repeat - generate code for a bounded repetition, recursively if needed
946 repeat(struct parse *p,
947 sopno start, /* operand from here to end of strip */
948 int from, /* repeated from this number */
949 int to) /* to this number of times (maybe INFINITY) */
951 sopno finish = HERE();
954 # define REP(f, t) ((f)*8 + (t))
955 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
958 if (p->error != 0) /* head off possible runaway recursion */
963 switch (REP(MAP(from), MAP(to))) {
964 case REP(0, 0): /* must be user doing this */
965 DROP(finish-start); /* drop the operand */
967 case REP(0, 1): /* as x{1,1}? */
968 case REP(0, N): /* as x{1,n}? */
969 case REP(0, INF): /* as x{1,}? */
970 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
971 INSERT(OCH_, start); /* offset is wrong... */
972 repeat(p, start+1, 1, to);
974 AHEAD(start); /* ... fix it */
977 ASTERN(O_CH, THERETHERE());
979 case REP(1, 1): /* trivial case */
982 case REP(1, N): /* as x?x{1,n-1} */
983 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
987 EMIT(OOR2, 0); /* offset very wrong... */
988 AHEAD(THERE()); /* ...so fix it */
989 ASTERN(O_CH, THERETHERE());
990 copy = dupl(p, start+1, finish+1);
991 assert(copy == finish+4);
992 repeat(p, copy, 1, to-1);
994 case REP(1, INF): /* as x+ */
995 INSERT(OPLUS_, start);
996 ASTERN(O_PLUS, start);
998 case REP(N, N): /* as xx{m-1,n-1} */
999 copy = dupl(p, start, finish);
1000 repeat(p, copy, from-1, to-1);
1002 case REP(N, INF): /* as xx{n-1,INF} */
1003 copy = dupl(p, start, finish);
1004 repeat(p, copy, from-1, to);
1006 default: /* "can't happen" */
1007 SETERROR(REG_ASSERT); /* just in case */
1013 - seterr - set an error condition
1015 static int /* useless but makes type checking happy */
1016 seterr(struct parse *p, int e)
1018 if (p->error == 0) /* keep earliest error condition */
1020 p->next = nuls; /* try to bring things to a halt */
1022 return(0); /* make the return value well-defined */
1026 - allocset - allocate a set of characters for []
1029 allocset(struct parse *p)
1031 int no = p->g->ncsets++;
1035 size_t css = (size_t)p->g->csetsize;
1038 if (no >= p->ncsalloc) { /* need another column of space */
1041 p->ncsalloc += CHAR_BIT;
1043 assert(nc % CHAR_BIT == 0);
1044 nbytes = nc / CHAR_BIT * css;
1046 ptr = (cset *)realloc((char *)p->g->sets, nc * sizeof(cset));
1051 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1054 p->g->setbits = ptr;
1056 for (i = 0; i < no; i++)
1057 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1059 (void) memset((char *)p->g->setbits + (nbytes - css), 0, css);
1061 /* XXX should not happen */
1062 if (p->g->sets == NULL || p->g->setbits == NULL)
1065 cs = &p->g->sets[no];
1066 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1067 cs->mask = 1 << ((no) % CHAR_BIT);
1076 free(p->g->setbits);
1077 p->g->setbits = NULL;
1079 SETERROR(REG_ESPACE);
1080 /* caller's responsibility not to do set ops */
1085 - freeset - free a now-unused set
1088 freeset(struct parse *p, cset *cs)
1091 cset *top = &p->g->sets[p->g->ncsets];
1092 size_t css = (size_t)p->g->csetsize;
1094 for (i = 0; i < css; i++)
1096 if (cs == top-1) /* recover only the easy case */
1101 - freezeset - final processing on a set of characters
1103 * The main task here is merging identical sets. This is usually a waste
1104 * of time (although the hash code minimizes the overhead), but can win
1105 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1106 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1109 static int /* set number */
1110 freezeset(struct parse *p, cset *cs)
1114 cset *top = &p->g->sets[p->g->ncsets];
1116 size_t css = (size_t)p->g->csetsize;
1118 /* look for an earlier one which is the same */
1119 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1120 if (cs2->hash == h && cs2 != cs) {
1122 for (i = 0; i < css; i++)
1123 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1129 if (cs2 < top) { /* found one */
1134 return((int)(cs - p->g->sets));
1138 - firstch - return first character in a set (which must have at least one)
1140 static int /* character; there is no "none" value */
1141 firstch(struct parse *p, cset *cs)
1144 size_t css = (size_t)p->g->csetsize;
1146 for (i = 0; i < css; i++)
1150 return(0); /* arbitrary */
1154 - nch - number of characters in a set
1157 nch(struct parse *p, cset *cs)
1160 size_t css = (size_t)p->g->csetsize;
1163 for (i = 0; i < css; i++)
1170 - mcadd - add a collating element to a cset
1173 mcadd( struct parse *p, cset *cs, const char *cp)
1175 size_t oldend = cs->smultis;
1178 cs->smultis += strlen(cp) + 1;
1179 np = realloc(cs->multis, cs->smultis);
1184 SETERROR(REG_ESPACE);
1189 llvm_strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1193 - mcinvert - invert the list of collating elements in a cset
1195 * This would have to know the set of possibilities. Implementation
1200 mcinvert(struct parse *p, cset *cs)
1202 assert(cs->multis == NULL); /* xxx */
1206 - mccase - add case counterparts of the list of collating elements in a cset
1208 * This would have to know the set of possibilities. Implementation
1213 mccase(struct parse *p, cset *cs)
1215 assert(cs->multis == NULL); /* xxx */
1219 - isinsets - is this character in any sets?
1221 static int /* predicate */
1222 isinsets(struct re_guts *g, int c)
1226 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1227 unsigned uc = (uch)c;
1229 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1236 - samesets - are these two characters in exactly the same sets?
1238 static int /* predicate */
1239 samesets(struct re_guts *g, int c1, int c2)
1243 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1244 unsigned uc1 = (uch)c1;
1245 unsigned uc2 = (uch)c2;
1247 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1248 if (col[uc1] != col[uc2])
1254 - categorize - sort out character categories
1257 categorize(struct parse *p, struct re_guts *g)
1259 cat_t *cats = g->categories;
1264 /* avoid making error situations worse */
1268 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1269 if (cats[c] == 0 && isinsets(g, c)) {
1270 cat = g->ncategories++;
1272 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1273 if (cats[c2] == 0 && samesets(g, c, c2))
1279 - dupl - emit a duplicate of a bunch of sops
1281 static sopno /* start of duplicate */
1282 dupl(struct parse *p,
1283 sopno start, /* from here */
1284 sopno finish) /* to this less one */
1287 sopno len = finish - start;
1289 assert(finish >= start);
1292 enlarge(p, p->ssize + len); /* this many unexpected additions */
1293 assert(p->ssize >= p->slen + len);
1294 (void) memmove((char *)(p->strip + p->slen),
1295 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1301 - doemit - emit a strip operator
1303 * It might seem better to implement this as a macro with a function as
1304 * hard-case backup, but it's just too big and messy unless there are
1305 * some changes to the data structures. Maybe later.
1308 doemit(struct parse *p, sop op, size_t opnd)
1310 /* avoid making error situations worse */
1314 /* deal with oversize operands ("can't happen", more or less) */
1315 assert(opnd < 1<<OPSHIFT);
1317 /* deal with undersized strip */
1318 if (p->slen >= p->ssize)
1319 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1320 assert(p->slen < p->ssize);
1322 /* finally, it's all reduced to the easy case */
1323 p->strip[p->slen++] = SOP(op, opnd);
1327 - doinsert - insert a sop into the strip
1330 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1336 /* avoid making error situations worse */
1341 EMIT(op, opnd); /* do checks, ensure space */
1342 assert(HERE() == sn+1);
1345 /* adjust paren pointers */
1347 for (i = 1; i < NPAREN; i++) {
1348 if (p->pbegin[i] >= pos) {
1351 if (p->pend[i] >= pos) {
1356 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1357 (HERE()-pos-1)*sizeof(sop));
1362 - dofwd - complete a forward reference
1365 dofwd(struct parse *p, sopno pos, sop value)
1367 /* avoid making error situations worse */
1371 assert(value < 1<<OPSHIFT);
1372 p->strip[pos] = OP(p->strip[pos]) | value;
1376 - enlarge - enlarge the strip
1379 enlarge(struct parse *p, sopno size)
1383 if (p->ssize >= size)
1386 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1388 SETERROR(REG_ESPACE);
1396 - stripsnug - compact the strip
1399 stripsnug(struct parse *p, struct re_guts *g)
1401 g->nstates = p->slen;
1402 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1403 if (g->strip == NULL) {
1404 SETERROR(REG_ESPACE);
1405 g->strip = p->strip;
1410 - findmust - fill in must and mlen with longest mandatory literal string
1412 * This algorithm could do fancy things like analyzing the operands of |
1413 * for common subsequences. Someday. This code is simple and finds most
1414 * of the interesting cases.
1416 * Note that must and mlen got initialized during setup.
1419 findmust(struct parse *p, struct re_guts *g)
1422 sop *start = 0; /* start initialized in the default case, after that */
1423 sop *newstart = 0; /* newstart was initialized in the OCHAR case */
1429 /* avoid making error situations worse */
1433 /* find the longest OCHAR sequence in strip */
1435 scan = g->strip + 1;
1439 case OCHAR: /* sequence member */
1440 if (newlen == 0) /* new sequence */
1441 newstart = scan - 1;
1444 case OPLUS_: /* things that don't break one */
1448 case OQUEST_: /* things that must be skipped */
1454 /* assert() interferes w debug printouts */
1455 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1457 g->iflags |= REGEX_BAD;
1460 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1462 default: /* things that break a sequence */
1463 if (newlen > g->mlen) { /* ends one */
1470 } while (OP(s) != OEND);
1472 if (g->mlen == 0) /* there isn't one */
1475 /* turn it into a character string */
1476 g->must = malloc((size_t)g->mlen + 1);
1477 if (g->must == NULL) { /* argh; just forget it */
1483 for (i = g->mlen; i > 0; i--) {
1484 while (OP(s = *scan++) != OCHAR)
1486 assert(cp < g->must + g->mlen);
1487 *cp++ = (char)OPND(s);
1489 assert(cp == g->must + g->mlen);
1490 *cp++ = '\0'; /* just on general principles */
1494 - pluscount - count + nesting
1496 static sopno /* nesting depth */
1497 pluscount(struct parse *p, struct re_guts *g)
1505 return(0); /* there may not be an OEND */
1507 scan = g->strip + 1;
1515 if (plusnest > maxnest)
1520 } while (OP(s) != OEND);
1522 g->iflags |= REGEX_BAD;