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
145 #define INFINITY (DUPMAX + 1)
148 static int never = 0; /* for use in asserts; shuts lint up */
150 #define never 0 /* some <assert.h>s have bugs too */
154 - llvm_regcomp - interface for parser and compilation
156 int /* 0 success, otherwise REG_something */
157 llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
161 struct parse *p = &pa;
165 # define GOODFLAGS(f) (f)
167 # define GOODFLAGS(f) ((f)&~REG_DUMP)
170 cflags = GOODFLAGS(cflags);
171 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
174 if (cflags®_PEND) {
175 if (preg->re_endp < pattern)
177 len = preg->re_endp - pattern;
179 len = strlen((const char *)pattern);
181 /* do the mallocs early so failure handling is easy */
182 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
183 (NC-1)*sizeof(cat_t));
186 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
187 p->strip = (sop *)calloc(p->ssize, sizeof(sop));
189 if (p->strip == NULL) {
196 p->next = (char *)pattern; /* convenience; we do not modify it */
197 p->end = p->next + len;
200 for (i = 0; i < NPAREN; i++) {
215 g->ncategories = 1; /* category 0 is "everything else" */
216 g->categories = &g->catspace[-(CHAR_MIN)];
217 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
222 g->firststate = THERE();
223 if (cflags®_EXTENDED)
225 else if (cflags®_NOSPEC)
230 g->laststate = THERE();
232 /* tidy up loose ends and fill things in */
236 g->nplus = pluscount(p, g);
238 preg->re_nsub = g->nsub;
240 preg->re_magic = MAGIC1;
242 /* not debugging, so can't rely on the assert() in llvm_regexec() */
243 if (g->iflags®EX_BAD)
244 SETERROR(REG_ASSERT);
247 /* win or lose, we're done */
248 if (p->error != 0) /* lose */
254 - p_ere - ERE parser top level, concatenation and alternation
257 p_ere(struct parse *p, int stop) /* character this ERE should end at */
263 int first = 1; /* is this the first alternative? */
266 /* do a bunch of concatenated expressions */
268 while (MORE() && (c = PEEK()) != '|' && c != stop)
270 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
273 break; /* NOTE BREAK OUT */
276 INSERT(OCH_, conc); /* offset is wrong */
281 ASTERN(OOR1, prevback);
283 AHEAD(prevfwd); /* fix previous offset */
285 EMIT(OOR2, 0); /* offset is very wrong */
288 if (!first) { /* tail-end fixups */
290 ASTERN(O_CH, prevback);
293 assert(!MORE() || SEE(stop));
297 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
300 p_ere_exp(struct parse *p)
310 assert(MORE()); /* caller should have ensured this */
316 REQUIRE(MORE(), REG_EPAREN);
320 p->pbegin[subno] = HERE();
321 EMIT(OLPAREN, subno);
324 if (subno < NPAREN) {
325 p->pend[subno] = HERE();
326 assert(p->pend[subno] != 0);
328 EMIT(ORPAREN, subno);
329 MUSTEAT(')', REG_EPAREN);
331 #ifndef POSIX_MISTAKE
332 case ')': /* happens only if no current unmatched ( */
334 * You may ask, why the ifndef? Because I didn't notice
335 * this until slightly too late for 1003.2, and none of the
336 * other 1003.2 regular-expression reviewers noticed it at
337 * all. So an unmatched ) is legal POSIX, at least until
338 * we can get it fixed.
340 SETERROR(REG_EPAREN);
345 p->g->iflags |= USEBOL;
351 p->g->iflags |= USEEOL;
360 SETERROR(REG_BADRPT);
363 if (p->g->cflags®_NEWLINE)
372 REQUIRE(MORE(), REG_EESCAPE);
374 if (c >= '1' && c <= '9') {
375 /* \[0-9] is taken to be a back-reference to a previously specified
376 * matching group. backrefnum will hold the number. The matching
377 * group must exist (i.e. if \4 is found there must have been at
378 * least 4 matching groups specified in the pattern previously).
380 backrefnum = c - '0';
381 if (p->pend[backrefnum] == 0) {
382 SETERROR(REG_ESUBREG);
386 /* Make sure everything checks out and emit the sequence
387 * that marks a back-reference to the parse structure.
389 assert(backrefnum <= p->g->nsub);
390 EMIT(OBACK_, backrefnum);
391 assert(p->pbegin[backrefnum] != 0);
392 assert(OP(p->strip[p->pbegin[backrefnum]]) != OLPAREN);
393 assert(OP(p->strip[p->pend[backrefnum]]) != ORPAREN);
394 (void) dupl(p, p->pbegin[backrefnum]+1, p->pend[backrefnum]);
395 EMIT(O_BACK, backrefnum);
398 /* Other chars are simply themselves when escaped with a backslash.
403 case '{': /* okay as ordinary except if digit follows */
404 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
414 /* we call { a repetition if followed by a digit */
415 if (!( c == '*' || c == '+' || c == '?' ||
416 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
417 return; /* no repetition, we're done */
420 REQUIRE(!wascaret, REG_BADRPT);
422 case '*': /* implemented as +? */
423 /* this case does not require the (y|) trick, noKLUDGE */
426 INSERT(OQUEST_, pos);
427 ASTERN(O_QUEST, pos);
434 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
435 INSERT(OCH_, pos); /* offset slightly wrong */
436 ASTERN(OOR1, pos); /* this one's right */
437 AHEAD(pos); /* fix the OCH_ */
438 EMIT(OOR2, 0); /* offset very wrong... */
439 AHEAD(THERE()); /* ...so fix it */
440 ASTERN(O_CH, THERETHERE());
445 if (isdigit((uch)PEEK())) {
447 REQUIRE(count <= count2, REG_BADBR);
448 } else /* single number with comma */
450 } else /* just a single number */
452 repeat(p, pos, count, count2);
453 if (!EAT('}')) { /* error heuristics */
454 while (MORE() && PEEK() != '}')
456 REQUIRE(MORE(), REG_EBRACE);
465 if (!( c == '*' || c == '+' || c == '?' ||
466 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
468 SETERROR(REG_BADRPT);
472 - p_str - string (no metacharacters) "parser"
475 p_str(struct parse *p)
477 REQUIRE(MORE(), REG_EMPTY);
479 ordinary(p, GETNEXT());
483 - p_bre - BRE parser top level, anchoring and concatenation
484 * Giving end1 as OUT essentially eliminates the end1/end2 check.
486 * This implementation is a bit of a kludge, in that a trailing $ is first
487 * taken as an ordinary character and then revised to be an anchor. The
488 * only undesirable side effect is that '$' gets included as a character
489 * category in such cases. This is fairly harmless; not worth fixing.
490 * The amount of lookahead needed to avoid this kludge is excessive.
493 p_bre(struct parse *p,
494 int end1, /* first terminating character */
495 int end2) /* second terminating character */
497 sopno start = HERE();
498 int first = 1; /* first subexpression? */
503 p->g->iflags |= USEBOL;
506 while (MORE() && !SEETWO(end1, end2)) {
507 wasdollar = p_simp_re(p, first);
510 if (wasdollar) { /* oops, that was a trailing anchor */
513 p->g->iflags |= USEEOL;
517 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
521 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
523 static int /* was the simple RE an unbackslashed $? */
524 p_simp_re(struct parse *p,
525 int starordinary) /* is a leading * an ordinary character? */
533 # define BACKSL (1<<CHAR_BIT)
535 pos = HERE(); /* repetition op, if any, covers from here */
537 assert(MORE()); /* caller should have ensured this */
540 REQUIRE(MORE(), REG_EESCAPE);
541 c = BACKSL | GETNEXT();
545 if (p->g->cflags®_NEWLINE)
554 SETERROR(REG_BADRPT);
560 p->pbegin[subno] = HERE();
561 EMIT(OLPAREN, subno);
562 /* the MORE here is an error heuristic */
563 if (MORE() && !SEETWO('\\', ')'))
565 if (subno < NPAREN) {
566 p->pend[subno] = HERE();
567 assert(p->pend[subno] != 0);
569 EMIT(ORPAREN, subno);
570 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
572 case BACKSL|')': /* should not get here -- must be user */
574 SETERROR(REG_EPAREN);
585 i = (c&~BACKSL) - '0';
587 if (p->pend[i] != 0) {
588 assert(i <= p->g->nsub);
590 assert(p->pbegin[i] != 0);
591 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
592 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
593 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
596 SETERROR(REG_ESUBREG);
600 REQUIRE(starordinary, REG_BADRPT);
603 ordinary(p, (char)c);
607 if (EAT('*')) { /* implemented as +? */
608 /* this case does not require the (y|) trick, noKLUDGE */
611 INSERT(OQUEST_, pos);
612 ASTERN(O_QUEST, pos);
613 } else if (EATTWO('\\', '{')) {
616 if (MORE() && isdigit((uch)PEEK())) {
618 REQUIRE(count <= count2, REG_BADBR);
619 } else /* single number with comma */
621 } else /* just a single number */
623 repeat(p, pos, count, count2);
624 if (!EATTWO('\\', '}')) { /* error heuristics */
625 while (MORE() && !SEETWO('\\', '}'))
627 REQUIRE(MORE(), REG_EBRACE);
630 } else if (c == '$') /* $ (but not \$) ends it */
637 - p_count - parse a repetition count
639 static int /* the value */
640 p_count(struct parse *p)
645 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
646 count = count*10 + (GETNEXT() - '0');
650 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
655 - p_bracket - parse a bracketed character list
657 * Note a significant property of this code: if the allocset() did SETERROR,
658 * no set operations are done.
661 p_bracket(struct parse *p)
666 /* Dept of Truly Sickening Special-Case Kludges */
667 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
672 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
678 if ((cs = allocset(p)) == NULL) {
679 /* allocset did set error status in p */
684 invert++; /* make note to invert set at end */
689 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
693 MUSTEAT(']', REG_EBRACK);
695 if (p->error != 0) { /* don't mess things up further */
700 if (p->g->cflags®_ICASE) {
704 for (i = p->g->csetsize - 1; i >= 0; i--)
705 if (CHIN(cs, i) && isalpha(i)) {
710 if (cs->multis != NULL)
716 for (i = p->g->csetsize - 1; i >= 0; i--)
721 if (p->g->cflags®_NEWLINE)
723 if (cs->multis != NULL)
727 assert(cs->multis == NULL); /* xxx */
729 if (nch(p, cs) == 1) { /* optimize singleton sets */
730 ordinary(p, firstch(p, cs));
733 EMIT(OANYOF, freezeset(p, cs));
737 - p_b_term - parse one term of a bracketed character list
740 p_b_term(struct parse *p, cset *cs)
746 /* classify what we've got */
747 switch ((MORE()) ? PEEK() : '\0') {
749 c = (MORE2()) ? PEEK2() : '\0';
752 SETERROR(REG_ERANGE);
753 return; /* NOTE RETURN */
761 case ':': /* character class */
763 REQUIRE(MORE(), REG_EBRACK);
765 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
767 REQUIRE(MORE(), REG_EBRACK);
768 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
770 case '=': /* equivalence class */
772 REQUIRE(MORE(), REG_EBRACK);
774 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
776 REQUIRE(MORE(), REG_EBRACK);
777 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
779 default: /* symbol, ordinary character, or range */
780 /* xxx revision needed for multichar stuff */
781 start = p_b_symbol(p);
782 if (SEE('-') && MORE2() && PEEK2() != ']') {
788 finish = p_b_symbol(p);
791 /* xxx what about signed chars here... */
792 REQUIRE(start <= finish, REG_ERANGE);
793 for (i = start; i <= finish; i++)
800 - p_b_cclass - parse a character-class name and deal with it
803 p_b_cclass(struct parse *p, cset *cs)
811 while (MORE() && isalpha((uch)PEEK()))
814 for (cp = cclasses; cp->name != NULL; cp++)
815 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
817 if (cp->name == NULL) {
818 /* oops, didn't find it */
819 SETERROR(REG_ECTYPE);
824 while ((c = *u++) != '\0')
826 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
831 - p_b_eclass - parse an equivalence-class name and deal with it
833 * This implementation is incomplete. xxx
836 p_b_eclass(struct parse *p, cset *cs)
840 c = p_b_coll_elem(p, '=');
845 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
847 static char /* value of symbol */
848 p_b_symbol(struct parse *p)
852 REQUIRE(MORE(), REG_EBRACK);
853 if (!EATTWO('[', '.'))
856 /* collating symbol */
857 value = p_b_coll_elem(p, '.');
858 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
863 - p_b_coll_elem - parse a collating-element name and look it up
865 static char /* value of collating element */
866 p_b_coll_elem(struct parse *p,
867 int endc) /* name ended by endc,']' */
873 while (MORE() && !SEETWO(endc, ']'))
876 SETERROR(REG_EBRACK);
880 for (cp = cnames; cp->name != NULL; cp++)
881 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
882 return(cp->code); /* known name */
884 return(*sp); /* single character */
885 SETERROR(REG_ECOLLATE); /* neither */
890 - othercase - return the case counterpart of an alphabetic
892 static char /* if no counterpart, return ch */
898 return ((uch)tolower(ch));
899 else if (islower(ch))
900 return ((uch)toupper(ch));
901 else /* peculiar, but could happen */
906 - bothcases - emit a dualcase version of a two-case character
908 * Boy, is this implementation ever a kludge...
911 bothcases(struct parse *p, int ch)
913 char *oldnext = p->next;
914 char *oldend = p->end;
918 assert(othercase(ch) != ch); /* p_bracket() would recurse */
925 assert(p->next == bracket+2);
931 - ordinary - emit an ordinary character
934 ordinary(struct parse *p, int ch)
936 cat_t *cap = p->g->categories;
938 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
941 EMIT(OCHAR, (uch)ch);
943 cap[ch] = p->g->ncategories++;
948 - nonnewline - emit REG_NEWLINE version of OANY
950 * Boy, is this implementation ever a kludge...
953 nonnewline(struct parse *p)
955 char *oldnext = p->next;
956 char *oldend = p->end;
966 assert(p->next == bracket+3);
972 - repeat - generate code for a bounded repetition, recursively if needed
975 repeat(struct parse *p,
976 sopno start, /* operand from here to end of strip */
977 int from, /* repeated from this number */
978 int to) /* to this number of times (maybe INFINITY) */
980 sopno finish = HERE();
983 # define REP(f, t) ((f)*8 + (t))
984 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
987 if (p->error != 0) /* head off possible runaway recursion */
992 switch (REP(MAP(from), MAP(to))) {
993 case REP(0, 0): /* must be user doing this */
994 DROP(finish-start); /* drop the operand */
996 case REP(0, 1): /* as x{1,1}? */
997 case REP(0, N): /* as x{1,n}? */
998 case REP(0, INF): /* as x{1,}? */
999 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1000 INSERT(OCH_, start); /* offset is wrong... */
1001 repeat(p, start+1, 1, to);
1002 ASTERN(OOR1, start);
1003 AHEAD(start); /* ... fix it */
1006 ASTERN(O_CH, THERETHERE());
1008 case REP(1, 1): /* trivial case */
1011 case REP(1, N): /* as x?x{1,n-1} */
1012 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1013 INSERT(OCH_, start);
1014 ASTERN(OOR1, start);
1016 EMIT(OOR2, 0); /* offset very wrong... */
1017 AHEAD(THERE()); /* ...so fix it */
1018 ASTERN(O_CH, THERETHERE());
1019 copy = dupl(p, start+1, finish+1);
1020 assert(copy == finish+4);
1021 repeat(p, copy, 1, to-1);
1023 case REP(1, INF): /* as x+ */
1024 INSERT(OPLUS_, start);
1025 ASTERN(O_PLUS, start);
1027 case REP(N, N): /* as xx{m-1,n-1} */
1028 copy = dupl(p, start, finish);
1029 repeat(p, copy, from-1, to-1);
1031 case REP(N, INF): /* as xx{n-1,INF} */
1032 copy = dupl(p, start, finish);
1033 repeat(p, copy, from-1, to);
1035 default: /* "can't happen" */
1036 SETERROR(REG_ASSERT); /* just in case */
1042 - seterr - set an error condition
1044 static int /* useless but makes type checking happy */
1045 seterr(struct parse *p, int e)
1047 if (p->error == 0) /* keep earliest error condition */
1049 p->next = nuls; /* try to bring things to a halt */
1051 return(0); /* make the return value well-defined */
1055 - allocset - allocate a set of characters for []
1058 allocset(struct parse *p)
1060 int no = p->g->ncsets++;
1064 size_t css = (size_t)p->g->csetsize;
1067 if (no >= p->ncsalloc) { /* need another column of space */
1070 p->ncsalloc += CHAR_BIT;
1072 assert(nc % CHAR_BIT == 0);
1073 nbytes = nc / CHAR_BIT * css;
1075 ptr = (cset *)realloc((char *)p->g->sets, nc * sizeof(cset));
1080 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1083 p->g->setbits = ptr;
1085 for (i = 0; i < no; i++)
1086 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1088 (void) memset((char *)p->g->setbits + (nbytes - css), 0, css);
1090 /* XXX should not happen */
1091 if (p->g->sets == NULL || p->g->setbits == NULL)
1094 cs = &p->g->sets[no];
1095 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1096 cs->mask = 1 << ((no) % CHAR_BIT);
1105 free(p->g->setbits);
1106 p->g->setbits = NULL;
1108 SETERROR(REG_ESPACE);
1109 /* caller's responsibility not to do set ops */
1114 - freeset - free a now-unused set
1117 freeset(struct parse *p, cset *cs)
1120 cset *top = &p->g->sets[p->g->ncsets];
1121 size_t css = (size_t)p->g->csetsize;
1123 for (i = 0; i < css; i++)
1125 if (cs == top-1) /* recover only the easy case */
1130 - freezeset - final processing on a set of characters
1132 * The main task here is merging identical sets. This is usually a waste
1133 * of time (although the hash code minimizes the overhead), but can win
1134 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1135 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1138 static int /* set number */
1139 freezeset(struct parse *p, cset *cs)
1143 cset *top = &p->g->sets[p->g->ncsets];
1145 size_t css = (size_t)p->g->csetsize;
1147 /* look for an earlier one which is the same */
1148 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1149 if (cs2->hash == h && cs2 != cs) {
1151 for (i = 0; i < css; i++)
1152 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1158 if (cs2 < top) { /* found one */
1163 return((int)(cs - p->g->sets));
1167 - firstch - return first character in a set (which must have at least one)
1169 static int /* character; there is no "none" value */
1170 firstch(struct parse *p, cset *cs)
1173 size_t css = (size_t)p->g->csetsize;
1175 for (i = 0; i < css; i++)
1179 return(0); /* arbitrary */
1183 - nch - number of characters in a set
1186 nch(struct parse *p, cset *cs)
1189 size_t css = (size_t)p->g->csetsize;
1192 for (i = 0; i < css; i++)
1199 - mcadd - add a collating element to a cset
1202 mcadd( struct parse *p, cset *cs, const char *cp)
1204 size_t oldend = cs->smultis;
1207 cs->smultis += strlen(cp) + 1;
1208 np = realloc(cs->multis, cs->smultis);
1213 SETERROR(REG_ESPACE);
1218 llvm_strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1222 - mcinvert - invert the list of collating elements in a cset
1224 * This would have to know the set of possibilities. Implementation
1229 mcinvert(struct parse *p, cset *cs)
1231 assert(cs->multis == NULL); /* xxx */
1235 - mccase - add case counterparts of the list of collating elements in a cset
1237 * This would have to know the set of possibilities. Implementation
1242 mccase(struct parse *p, cset *cs)
1244 assert(cs->multis == NULL); /* xxx */
1248 - isinsets - is this character in any sets?
1250 static int /* predicate */
1251 isinsets(struct re_guts *g, int c)
1255 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1256 unsigned uc = (uch)c;
1258 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1265 - samesets - are these two characters in exactly the same sets?
1267 static int /* predicate */
1268 samesets(struct re_guts *g, int c1, int c2)
1272 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1273 unsigned uc1 = (uch)c1;
1274 unsigned uc2 = (uch)c2;
1276 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1277 if (col[uc1] != col[uc2])
1283 - categorize - sort out character categories
1286 categorize(struct parse *p, struct re_guts *g)
1288 cat_t *cats = g->categories;
1293 /* avoid making error situations worse */
1297 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1298 if (cats[c] == 0 && isinsets(g, c)) {
1299 cat = g->ncategories++;
1301 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1302 if (cats[c2] == 0 && samesets(g, c, c2))
1308 - dupl - emit a duplicate of a bunch of sops
1310 static sopno /* start of duplicate */
1311 dupl(struct parse *p,
1312 sopno start, /* from here */
1313 sopno finish) /* to this less one */
1316 sopno len = finish - start;
1318 assert(finish >= start);
1321 enlarge(p, p->ssize + len); /* this many unexpected additions */
1322 assert(p->ssize >= p->slen + len);
1323 (void) memmove((char *)(p->strip + p->slen),
1324 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1330 - doemit - emit a strip operator
1332 * It might seem better to implement this as a macro with a function as
1333 * hard-case backup, but it's just too big and messy unless there are
1334 * some changes to the data structures. Maybe later.
1337 doemit(struct parse *p, sop op, size_t opnd)
1339 /* avoid making error situations worse */
1343 /* deal with oversize operands ("can't happen", more or less) */
1344 assert(opnd < 1<<OPSHIFT);
1346 /* deal with undersized strip */
1347 if (p->slen >= p->ssize)
1348 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1349 assert(p->slen < p->ssize);
1351 /* finally, it's all reduced to the easy case */
1352 p->strip[p->slen++] = SOP(op, opnd);
1356 - doinsert - insert a sop into the strip
1359 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1365 /* avoid making error situations worse */
1370 EMIT(op, opnd); /* do checks, ensure space */
1371 assert(HERE() == sn+1);
1374 /* adjust paren pointers */
1376 for (i = 1; i < NPAREN; i++) {
1377 if (p->pbegin[i] >= pos) {
1380 if (p->pend[i] >= pos) {
1385 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1386 (HERE()-pos-1)*sizeof(sop));
1391 - dofwd - complete a forward reference
1394 dofwd(struct parse *p, sopno pos, sop value)
1396 /* avoid making error situations worse */
1400 assert(value < 1<<OPSHIFT);
1401 p->strip[pos] = OP(p->strip[pos]) | value;
1405 - enlarge - enlarge the strip
1408 enlarge(struct parse *p, sopno size)
1412 if (p->ssize >= size)
1415 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1417 SETERROR(REG_ESPACE);
1425 - stripsnug - compact the strip
1428 stripsnug(struct parse *p, struct re_guts *g)
1430 g->nstates = p->slen;
1431 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1432 if (g->strip == NULL) {
1433 SETERROR(REG_ESPACE);
1434 g->strip = p->strip;
1439 - findmust - fill in must and mlen with longest mandatory literal string
1441 * This algorithm could do fancy things like analyzing the operands of |
1442 * for common subsequences. Someday. This code is simple and finds most
1443 * of the interesting cases.
1445 * Note that must and mlen got initialized during setup.
1448 findmust(struct parse *p, struct re_guts *g)
1451 sop *start = 0; /* start initialized in the default case, after that */
1452 sop *newstart = 0; /* newstart was initialized in the OCHAR case */
1458 /* avoid making error situations worse */
1462 /* find the longest OCHAR sequence in strip */
1464 scan = g->strip + 1;
1468 case OCHAR: /* sequence member */
1469 if (newlen == 0) /* new sequence */
1470 newstart = scan - 1;
1473 case OPLUS_: /* things that don't break one */
1477 case OQUEST_: /* things that must be skipped */
1483 /* assert() interferes w debug printouts */
1484 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1486 g->iflags |= REGEX_BAD;
1489 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1491 default: /* things that break a sequence */
1492 if (newlen > g->mlen) { /* ends one */
1499 } while (OP(s) != OEND);
1501 if (g->mlen == 0) /* there isn't one */
1504 /* turn it into a character string */
1505 g->must = malloc((size_t)g->mlen + 1);
1506 if (g->must == NULL) { /* argh; just forget it */
1512 for (i = g->mlen; i > 0; i--) {
1513 while (OP(s = *scan++) != OCHAR)
1515 assert(cp < g->must + g->mlen);
1516 *cp++ = (char)OPND(s);
1518 assert(cp == g->must + g->mlen);
1519 *cp++ = '\0'; /* just on general principles */
1523 - pluscount - count + nesting
1525 static sopno /* nesting depth */
1526 pluscount(struct parse *p, struct re_guts *g)
1534 return(0); /* there may not be an OEND */
1536 scan = g->strip + 1;
1544 if (plusnest > maxnest)
1549 } while (OP(s) != OEND);
1551 g->iflags |= REGEX_BAD;