2 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
40 #if defined(LIBC_SCCS) && !defined(lint)
41 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
43 #endif /* LIBC_SCCS and not lint */
47 #include <sys/types.h>
55 #include "regex/regex.h"
56 #include "regex/utils.h"
57 #include "regex/regex2.h"
58 #include "regex/cclass.h"
59 #include "regex/cname.h"
62 * parse structure, passed up and down to avoid global variables and
67 pg_wchar *next; /* next character in RE */
68 pg_wchar *end; /* end of string (-> NUL normally) */
69 int error; /* has an error been seen? */
70 sop *strip; /* malloced strip */
71 sopno ssize; /* malloced strip size (allocated) */
72 sopno slen; /* malloced strip length (used) */
73 int ncsalloc; /* number of csets allocated */
75 #define NPAREN 10 /* we need to remember () 1-9 for back
77 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
78 sopno pend[NPAREN]; /* -> ) ([0] unused) */
81 /* ========= begin header generated by ./mkh ========= */
87 /* === regcomp.c === */
88 static void p_ere(struct parse * p, int stop);
89 static void p_ere_exp(struct parse * p);
90 static void p_str(struct parse * p);
91 static void p_bre(struct parse * p, int end1, int end2);
92 static int p_simp_re(struct parse * p, int starordinary);
93 static int p_count(struct parse * p);
94 static void p_bracket(struct parse * p);
95 static void p_b_term(struct parse * p, cset *cs);
96 static void p_b_cclass(struct parse * p, cset *cs);
97 static void p_b_eclass(struct parse * p, cset *cs);
98 static pg_wchar p_b_symbol(struct parse * p);
99 static char p_b_coll_elem(struct parse * p, int endc);
101 static unsigned char othercase(int ch);
103 static char othercase(int ch);
105 static void bothcases(struct parse * p, int ch);
106 static void ordinary(struct parse * p, int ch);
107 static void nonnewline(struct parse * p);
108 static void repeat(struct parse * p, sopno start, int from, int to);
109 static int seterr(struct parse * p, int e);
110 static cset *allocset(struct parse * p);
111 static void freeset(struct parse * p, cset *cs);
112 static int freezeset(struct parse * p, cset *cs);
113 static int firstch(struct parse * p, cset *cs);
114 static int nch(struct parse * p, cset *cs);
115 static void mcadd(struct parse * p, cset *cs, char *cp);
116 static void mcinvert(struct parse * p, cset *cs);
117 static void mccase(struct parse * p, cset *cs);
118 static int isinsets(struct re_guts * g, int c);
119 static int samesets(struct re_guts * g, int c1, int c2);
120 static void categorize(struct parse * p, struct re_guts * g);
121 static sopno dupl(struct parse * p, sopno start, sopno finish);
122 static void doemit(struct parse * p, sop op, size_t opnd);
123 static void doinsert(struct parse * p, sop op, size_t opnd, sopno pos);
124 static void dofwd(struct parse * p, sopno pos, sop value);
125 static void enlarge(struct parse * p, sopno size);
126 static void stripsnug(struct parse * p, struct re_guts * g);
127 static void findmust(struct parse * p, struct re_guts * g);
128 static sopno pluscount(struct parse * p, struct re_guts * g);
129 static int pg_isdigit(int c);
130 static int pg_isalpha(int c);
131 static int pg_isupper(int c);
132 static int pg_islower(int c);
138 /* ========= end header generated by ./mkh ========= */
140 static pg_wchar nuls[10]; /* place to point scanner in event of
144 * macros for use with parse structure
145 * BEWARE: these know that the parse structure is named `p' !!!
147 #define PEEK() (*p->next)
148 #define PEEK2() (*(p->next+1))
149 #define MORE() (p->next < p->end)
150 #define MORE2() (p->next+1 < p->end)
151 #define SEE(c) (MORE() && PEEK() == (c))
152 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
153 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
154 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
155 #define NEXT() (p->next++)
156 #define NEXT2() (p->next += 2)
157 #define NEXTn(n) (p->next += (n))
158 #define GETNEXT() (*p->next++)
159 #define SETERROR(e) seterr(p, (e))
160 #define REQUIRE(co, e) if (!(co)) SETERROR(e)
161 #define MUSTSEE(c, e) REQUIRE(MORE() && PEEK() == (c), e)
162 #define MUSTEAT(c, e) REQUIRE(MORE() && GETNEXT() == (c), e)
163 #define MUSTNOTSEE(c, e) REQUIRE(!MORE() || PEEK() != (c), e)
164 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
165 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
166 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
167 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
168 #define HERE() (p->slen)
169 #define THERE() (p->slen - 1)
170 #define THERETHERE() (p->slen - 2)
171 #define DROP(n) (p->slen -= (n))
174 static int never = 0; /* for use in asserts; shuts lint up */
177 #define never 0 /* some <assert.h>s have bugs too */
181 - regcomp - interface for parser and compilation
182 = extern int regcomp(regex_t *, const char *, int);
183 = #define REG_BASIC 0000
184 = #define REG_EXTENDED 0001
185 = #define REG_ICASE 0002
186 = #define REG_NOSUB 0004
187 = #define REG_NEWLINE 0010
188 = #define REG_NOSPEC 0020
189 = #define REG_PEND 0040
190 = #define REG_DUMP 0200
192 int /* 0 success, otherwise REG_something */
193 pg95_regcomp(preg, pattern, cflags)
200 struct parse *p = &pa;
210 #define GOODFLAGS(f) (f)
212 #define GOODFLAGS(f) ((f)&~REG_DUMP)
215 cflags = GOODFLAGS(cflags);
216 if ((cflags & REG_EXTENDED) && (cflags & REG_NOSPEC))
219 if (cflags & REG_PEND)
223 if (preg->re_endp < wcp)
225 len = preg->re_endp - wcp;
227 if (preg->re_endp < pattern)
229 len = preg->re_endp - pattern;
235 wcp = (pg_wchar *) malloc((strlen(pattern) + 1) * sizeof(pg_wchar));
239 (void) pg_mb2wchar((unsigned char *) pattern, wcp);
240 len = pg_wchar_strlen(wcp);
243 len = strlen((char *) pattern);
247 /* do the mallocs early so failure handling is easy */
248 g = (struct re_guts *) malloc(sizeof(struct re_guts) +
249 (NC - 1) * sizeof(cat_t));
252 p->ssize = len / (size_t) 2 *(size_t) 3 + (size_t) 1; /* ugh */
254 p->strip = (sop *) malloc(p->ssize * sizeof(sop));
256 if (p->strip == NULL)
267 p->next = (pg_wchar *) pattern; /* convenience; we do not modify
270 p->end = p->next + len;
273 for (i = 0; i < NPAREN; i++)
289 g->ncategories = 1; /* category 0 is "everything else" */
290 g->categories = &g->catspace[-(CHAR_MIN)];
291 memset((char *) g->catspace, 0, NC * sizeof(cat_t));
296 g->firststate = THERE();
297 if (cflags & REG_EXTENDED)
299 else if (cflags & REG_NOSPEC)
304 g->laststate = THERE();
306 /* tidy up loose ends and fill things in */
310 g->nplus = pluscount(p, g);
312 preg->re_nsub = g->nsub;
314 preg->re_magic = MAGIC1;
316 /* not debugging, so can't rely on the assert() in regexec() */
318 SETERROR(REG_ASSERT);
321 /* win or lose, we're done */
322 if (p->error != 0) /* lose */
328 - p_ere - ERE parser top level, concatenation and alternation
329 == static void p_ere(struct parse *p, int stop);
334 int stop; /* character this ERE should end at */
340 int first = 1; /* is this the first alternative? */
344 /* do a bunch of concatenated expressions */
346 while (MORE() && (c = PEEK()) != '|' && c != stop)
348 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
351 break; /* NOTE BREAK OUT */
355 INSERT(OCH_, conc); /* offset is wrong */
360 ASTERN(OOR1, prevback);
362 AHEAD(prevfwd); /* fix previous offset */
364 EMIT(OOR2, 0); /* offset is very wrong */
368 { /* tail-end fixups */
370 ASTERN(O_CH, prevback);
373 assert(!MORE() || SEE(stop));
377 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
378 == static void p_ere_exp(struct parse *p);
391 assert(MORE()); /* caller should have ensured this */
398 REQUIRE(MORE(), REG_EPAREN);
402 p->pbegin[subno] = HERE();
403 EMIT(OLPAREN, subno);
408 p->pend[subno] = HERE();
409 assert(p->pend[subno] != 0);
411 EMIT(ORPAREN, subno);
412 MUSTEAT(')', REG_EPAREN);
414 #ifndef POSIX_MISTAKE
415 case ')': /* happens only if no current unmatched ( */
418 * You may ask, why the ifndef? Because I didn't notice this
419 * until slightly too late for 1003.2, and none of the other
420 * 1003.2 regular-expression reviewers noticed it at all. So
421 * an unmatched ) is legal POSIX, at least until we can get it
424 SETERROR(REG_EPAREN);
429 p->g->iflags |= USEBOL;
435 p->g->iflags |= USEEOL;
444 SETERROR(REG_BADRPT);
447 if (p->g->cflags & REG_NEWLINE)
456 REQUIRE(MORE(), REG_EESCAPE);
460 case '{': /* okay as ordinary except if digit
462 REQUIRE(!MORE() || !pg_isdigit(PEEK()), REG_BADRPT);
472 /* we call { a repetition if followed by a digit */
473 if (!(c == '*' || c == '+' || c == '?' ||
474 (c == '{' && MORE2() && pg_isdigit(PEEK2()))))
475 return; /* no repetition, we're done */
478 REQUIRE(!wascaret, REG_BADRPT);
481 case '*': /* implemented as +? */
482 /* this case does not require the (y|) trick, noKLUDGE */
485 INSERT(OQUEST_, pos);
486 ASTERN(O_QUEST, pos);
493 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
494 INSERT(OCH_, pos); /* offset slightly wrong */
495 ASTERN(OOR1, pos); /* this one's right */
496 AHEAD(pos); /* fix the OCH_ */
497 EMIT(OOR2, 0); /* offset very wrong... */
498 AHEAD(THERE()); /* ...so fix it */
499 ASTERN(O_CH, THERETHERE());
505 if (pg_isdigit(PEEK()))
508 REQUIRE(count <= count2, REG_BADBR);
511 /* single number with comma */
515 /* just a single number */
517 repeat(p, pos, count, count2);
519 { /* error heuristics */
520 while (MORE() && PEEK() != '}')
522 REQUIRE(MORE(), REG_EBRACE);
531 if (!(c == '*' || c == '+' || c == '?' ||
532 (c == '{' && MORE2() && pg_isdigit(PEEK2()))))
534 SETERROR(REG_BADRPT);
538 - p_str - string (no metacharacters) "parser"
539 == static void p_str(struct parse *p);
545 REQUIRE(MORE(), REG_EMPTY);
547 ordinary(p, GETNEXT());
551 - p_bre - BRE parser top level, anchoring and concatenation
552 == static void p_bre(struct parse *p, int end1, \
554 * Giving end1 as OUT essentially eliminates the end1/end2 check.
556 * This implementation is a bit of a kludge, in that a trailing $ is first
557 * taken as an ordinary character and then revised to be an anchor. The
558 * only undesirable side effect is that '$' gets included as a character
559 * category in such cases. This is fairly harmless; not worth fixing.
560 * The amount of lookahead needed to avoid this kludge is excessive.
565 int end1; /* first terminating character */
566 int end2; /* second terminating character */
568 sopno start = HERE();
569 int first = 1; /* first subexpression? */
575 p->g->iflags |= USEBOL;
578 while (MORE() && !SEETWO(end1, end2))
580 wasdollar = p_simp_re(p, first);
584 { /* oops, that was a trailing anchor */
587 p->g->iflags |= USEEOL;
591 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
595 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
596 == static int p_simp_re(struct parse *p, int starordinary);
598 static int /* was the simple RE an unbackslashed $? */
599 p_simp_re(p, starordinary)
601 int starordinary; /* is a leading * an ordinary character? */
610 #define BACKSL (1<<24)
612 pos = HERE(); /* repetion op, if any, covers from here */
614 assert(MORE()); /* caller should have ensured this */
618 REQUIRE(MORE(), REG_EESCAPE);
620 c = BACKSL | (pg_wchar) GETNEXT();
622 c = BACKSL | (unsigned char) GETNEXT();
628 if (p->g->cflags & REG_NEWLINE)
637 SETERROR(REG_BADRPT);
643 p->pbegin[subno] = HERE();
644 EMIT(OLPAREN, subno);
645 /* the MORE here is an error heuristic */
646 if (MORE() && !SEETWO('\\', ')'))
650 p->pend[subno] = HERE();
651 assert(p->pend[subno] != 0);
653 EMIT(ORPAREN, subno);
654 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
656 case BACKSL | ')': /* should not get here -- must be user */
658 SETERROR(REG_EPAREN);
669 i = (c & ~BACKSL) - '0';
673 assert(i <= p->g->nsub);
675 assert(p->pbegin[i] != 0);
676 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
677 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
678 dupl(p, p->pbegin[i] + 1, p->pend[i]);
682 SETERROR(REG_ESUBREG);
686 REQUIRE(starordinary, REG_BADRPT);
689 ordinary(p, c & ~BACKSL);
694 { /* implemented as +? */
695 /* this case does not require the (y|) trick, noKLUDGE */
698 INSERT(OQUEST_, pos);
699 ASTERN(O_QUEST, pos);
701 else if (EATTWO('\\', '{'))
706 if (MORE() && pg_isdigit(PEEK()))
709 REQUIRE(count <= count2, REG_BADBR);
712 /* single number with comma */
716 /* just a single number */
718 repeat(p, pos, count, count2);
719 if (!EATTWO('\\', '}'))
720 { /* error heuristics */
721 while (MORE() && !SEETWO('\\', '}'))
723 REQUIRE(MORE(), REG_EBRACE);
727 else if (c == (unsigned char) '$') /* $ (but not \$) ends it */
734 - p_count - parse a repetition count
735 == static int p_count(struct parse *p);
737 static int /* the value */
744 while (MORE() && pg_isdigit(PEEK()) && count <= DUPMAX)
746 count = count * 10 + (GETNEXT() - '0');
750 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
755 - p_bracket - parse a bracketed character list
756 == static void p_bracket(struct parse *p);
758 * Note a significant property of this code: if the allocset() did SETERROR,
759 * no set operations are done.
765 cset *cs = allocset(p);
769 pg_wchar sp1[] = {'[', ':', '<', ':', ']', ']'};
770 pg_wchar sp2[] = {'[', ':', '>', ':', ']', ']'};
774 /* Dept of Truly Sickening Special-Case Kludges */
776 if (p->next + 5 < p->end && pg_wchar_strncmp(p->next, sp1, 6) == 0)
778 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0)
786 if (p->next + 5 < p->end && pg_wchar_strncmp(p->next, sp2, 6) == 0)
788 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0)
797 invert++; /* make note to invert set at end */
802 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
806 MUSTEAT(']', REG_EBRACK);
808 if (p->error != 0) /* don't mess things up further */
811 if (p->g->cflags & REG_ICASE)
816 for (i = p->g->csetsize - 1; i >= 0; i--)
817 if (CHIN(cs, i) && pg_isalpha(i))
823 if (cs->multis != NULL)
830 for (i = p->g->csetsize - 1; i >= 0; i--)
835 if (p->g->cflags & REG_NEWLINE)
837 if (cs->multis != NULL)
841 assert(cs->multis == NULL); /* xxx */
844 { /* optimize singleton sets */
845 ordinary(p, firstch(p, cs));
849 EMIT(OANYOF, freezeset(p, cs));
853 - p_b_term - parse one term of a bracketed character list
854 == static void p_b_term(struct parse *p, cset *cs);
866 /* classify what we've got */
867 switch ((MORE()) ? PEEK() : '\0')
870 c = (MORE2()) ? PEEK2() : '\0';
873 SETERROR(REG_ERANGE);
874 return; /* NOTE RETURN */
883 case ':': /* character class */
885 REQUIRE(MORE(), REG_EBRACK);
887 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
889 REQUIRE(MORE(), REG_EBRACK);
890 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
892 case '=': /* equivalence class */
894 REQUIRE(MORE(), REG_EBRACK);
896 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
898 REQUIRE(MORE(), REG_EBRACK);
899 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
901 default: /* symbol, ordinary character, or range */
902 /* xxx revision needed for multichar stuff */
903 start = p_b_symbol(p);
904 if (SEE('-') && MORE2() && PEEK2() != ']')
911 finish = p_b_symbol(p);
915 /* xxx what about signed chars here... */
916 REQUIRE(start <= finish, REG_ERANGE);
918 if (CHlc(start) != CHlc(finish))
919 SETERROR(REG_ERANGE);
921 for (i = start; i <= finish; i++)
928 - p_b_cclass - parse a character-class name and deal with it
929 == static void p_b_cclass(struct parse *p, cset *cs);
936 pg_wchar *sp = p->next;
942 while (MORE() && pg_isalpha(PEEK()))
945 for (cp = cclasses; cp->name != NULL; cp++)
947 if (pg_char_and_wchar_strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
949 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
952 if (cp->name == NULL)
954 /* oops, didn't find it */
955 SETERROR(REG_ECTYPE);
960 while ((c = *u++) != '\0')
962 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
967 - p_b_eclass - parse an equivalence-class name and deal with it
968 == static void p_b_eclass(struct parse *p, cset *cs);
970 * This implementation is incomplete. xxx
979 c = p_b_coll_elem(p, '=');
984 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
985 == static char p_b_symbol(struct parse *p);
987 static pg_wchar /* value of symbol */
993 REQUIRE(MORE(), REG_EBRACK);
994 if (!EATTWO('[', '.'))
997 /* collating symbol */
998 value = p_b_coll_elem(p, '.');
999 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1004 - p_b_coll_elem - parse a collating-element name and look it up
1005 == static char p_b_coll_elem(struct parse *p, int endc);
1007 static char /* value of collating element */
1008 p_b_coll_elem(p, endc)
1010 int endc; /* name ended by endc,']' */
1012 pg_wchar *sp = p->next;
1016 while (MORE() && !SEETWO(endc, ']'))
1020 SETERROR(REG_EBRACK);
1024 for (cp = cnames; cp->name != NULL; cp++)
1026 if (pg_char_and_wchar_strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
1028 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
1030 return cp->code; /* known name */
1032 return *sp; /* single character */
1033 SETERROR(REG_ECOLLATE); /* neither */
1038 - othercase - return the case counterpart of an alphabetic
1039 == static char othercase(int ch);
1042 static unsigned char /* if no counterpart, return ch */
1044 static char /* if no counterpart, return ch */
1049 assert(pg_isalpha(ch));
1052 return (unsigned char) tolower(ch);
1056 else if (pg_islower(ch))
1058 return (unsigned char) toupper(ch);
1063 /* peculiar, but could happen */
1065 return (unsigned char) ch;
1072 - bothcases - emit a dualcase version of a two-case character
1073 == static void bothcases(struct parse *p, int ch);
1075 * Boy, is this implementation ever a kludge...
1082 pg_wchar *oldnext = p->next;
1083 pg_wchar *oldend = p->end;
1084 pg_wchar bracket[3];
1086 assert(othercase(ch) != ch);/* p_bracket() would recurse */
1088 p->end = bracket + 2;
1093 assert(p->next == bracket + 2);
1099 - ordinary - emit an ordinary character
1100 == static void ordinary(struct parse *p, int ch);
1107 cat_t *cap = p->g->categories;
1109 if ((p->g->cflags & REG_ICASE) && pg_isalpha(ch) && othercase(ch) != ch)
1114 EMIT(OCHAR, (pg_wchar) ch);
1116 EMIT(OCHAR, (unsigned char) ch);
1118 if (ch >= CHAR_MIN && ch <= CHAR_MAX && cap[ch] == 0)
1119 cap[ch] = p->g->ncategories++;
1124 - nonnewline - emit REG_NEWLINE version of OANY
1125 == static void nonnewline(struct parse *p);
1127 * Boy, is this implementation ever a kludge...
1133 pg_wchar *oldnext = p->next;
1134 pg_wchar *oldend = p->end;
1135 pg_wchar bracket[4];
1138 p->end = bracket + 3;
1144 assert(p->next == bracket + 3);
1150 - repeat - generate code for a bounded repetition, recursively if needed
1151 == static void repeat(struct parse *p, sopno start, int from, int to);
1154 repeat(p, start, from, to)
1156 sopno start; /* operand from here to end of strip */
1157 int from; /* repeated from this number */
1158 int to; /* to this number of times (maybe
1161 sopno finish = HERE();
1165 #define REP(f, t) ((f)*8 + (t))
1166 #define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1169 if (p->error != 0) /* head off possible runaway recursion */
1174 switch (REP(MAP(from), MAP(to)))
1176 case REP(0, 0): /* must be user doing this */
1177 DROP(finish - start); /* drop the operand */
1179 case REP(0, 1): /* as x{1,1}? */
1180 case REP(0, N): /* as x{1,n}? */
1181 case REP(0, INF): /* as x{1,}? */
1182 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1183 INSERT(OCH_, start);/* offset is wrong... */
1184 repeat(p, start + 1, 1, to);
1185 ASTERN(OOR1, start);
1186 AHEAD(start); /* ... fix it */
1189 ASTERN(O_CH, THERETHERE());
1191 case REP(1, 1): /* trivial case */
1194 case REP(1, N): /* as x?x{1,n-1} */
1195 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1196 INSERT(OCH_, start);
1197 ASTERN(OOR1, start);
1199 EMIT(OOR2, 0); /* offset very wrong... */
1200 AHEAD(THERE()); /* ...so fix it */
1201 ASTERN(O_CH, THERETHERE());
1202 copy = dupl(p, start + 1, finish + 1);
1203 assert(copy == finish + 4);
1204 repeat(p, copy, 1, to - 1);
1206 case REP(1, INF): /* as x+ */
1207 INSERT(OPLUS_, start);
1208 ASTERN(O_PLUS, start);
1210 case REP(N, N): /* as xx{m-1,n-1} */
1211 copy = dupl(p, start, finish);
1212 repeat(p, copy, from - 1, to - 1);
1214 case REP(N, INF): /* as xx{n-1,INF} */
1215 copy = dupl(p, start, finish);
1216 repeat(p, copy, from - 1, to);
1218 default: /* "can't happen" */
1219 SETERROR(REG_ASSERT); /* just in case */
1225 - seterr - set an error condition
1226 == static int seterr(struct parse *p, int e);
1228 static int /* useless but makes type checking happy */
1233 if (p->error == 0) /* keep earliest error condition */
1235 p->next = nuls; /* try to bring things to a halt */
1237 return 0; /* make the return value well-defined */
1241 - allocset - allocate a set of characters for []
1242 == static cset *allocset(struct parse *p);
1248 int no = p->g->ncsets++;
1252 size_t css = (size_t) p->g->csetsize;
1255 if (no >= p->ncsalloc)
1256 { /* need another column of space */
1257 p->ncsalloc += CHAR_BIT;
1259 assert(nc % CHAR_BIT == 0);
1260 nbytes = nc / CHAR_BIT * css;
1261 if (p->g->sets == NULL)
1262 p->g->sets = (cset *) malloc(nc * sizeof(cset));
1264 p->g->sets = (cset *) realloc((char *) p->g->sets,
1266 if (p->g->setbits == NULL)
1267 p->g->setbits = (uch *) malloc(nbytes);
1270 p->g->setbits = (uch *) realloc((char *) p->g->setbits,
1272 /* xxx this isn't right if setbits is now NULL */
1273 for (i = 0; i < no; i++)
1274 p->g->sets[i].ptr = p->g->setbits + css * (i / CHAR_BIT);
1276 if (p->g->sets != NULL && p->g->setbits != NULL)
1277 memset((char *) p->g->setbits + (nbytes - css),
1282 SETERROR(REG_ESPACE);
1283 /* caller's responsibility not to do set ops */
1287 assert(p->g->sets != NULL); /* xxx */
1288 cs = &p->g->sets[no];
1289 cs->ptr = p->g->setbits + css * ((no) / CHAR_BIT);
1290 cs->mask = 1 << ((no) % CHAR_BIT);
1299 - freeset - free a now-unused set
1300 == static void freeset(struct parse *p, cset *cs);
1308 cset *top = &p->g->sets[p->g->ncsets];
1309 size_t css = (size_t) p->g->csetsize;
1311 for (i = 0; i < css; i++)
1313 if (cs == top - 1) /* recover only the easy case */
1318 - freezeset - final processing on a set of characters
1319 == static int freezeset(struct parse *p, cset *cs);
1321 * The main task here is merging identical sets. This is usually a waste
1322 * of time (although the hash code minimizes the overhead), but can win
1323 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1324 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1327 static int /* set number */
1334 cset *top = &p->g->sets[p->g->ncsets];
1336 size_t css = (size_t) p->g->csetsize;
1338 /* look for an earlier one which is the same */
1339 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1340 if (cs2->hash == h && cs2 != cs)
1343 for (i = 0; i < css; i++)
1344 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1356 return (int) (cs - p->g->sets);
1360 - firstch - return first character in a set (which must have at least one)
1361 == static int firstch(struct parse *p, cset *cs);
1363 static int /* character; there is no "none" value */
1369 size_t css = (size_t) p->g->csetsize;
1371 for (i = 0; i < css; i++)
1375 return 0; /* arbitrary */
1379 - nch - number of characters in a set
1380 == static int nch(struct parse *p, cset *cs);
1388 size_t css = (size_t) p->g->csetsize;
1391 for (i = 0; i < css; i++)
1398 - mcadd - add a collating element to a cset
1399 == static void mcadd(struct parse *p, cset *cs, \
1408 size_t oldend = cs->smultis;
1410 cs->smultis += strlen(cp) + 1;
1411 if (cs->multis == NULL)
1412 cs->multis = malloc(cs->smultis);
1414 cs->multis = realloc(cs->multis, cs->smultis);
1415 if (cs->multis == NULL)
1417 SETERROR(REG_ESPACE);
1421 strcpy(cs->multis + oldend - 1, cp);
1422 cs->multis[cs->smultis - 1] = '\0';
1426 - mcsub - subtract a collating element from a cset
1427 == static void mcsub(cset *cs, char *cp);
1435 char *fp = mcfind(cs, cp);
1436 size_t len = strlen(fp);
1439 memmove(fp, fp + len + 1,
1440 cs->smultis - (fp + len + 1 - cs->multis));
1443 if (cs->smultis == 0) {
1449 cs->multis = realloc(cs->multis, cs->smultis);
1450 assert(cs->multis != NULL);
1455 - mcin - is a collating element in a cset?
1456 == static int mcin(cset *cs, char *cp);
1464 return(mcfind(cs, cp) != NULL);
1469 - mcfind - find a collating element in a cset
1470 == static char *mcfind(cset *cs, char *cp);
1480 if (cs->multis == NULL)
1482 for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
1483 if (strcmp(cp, p) == 0)
1489 - mcinvert - invert the list of collating elements in a cset
1490 == static void mcinvert(struct parse *p, cset *cs);
1492 * This would have to know the set of possibilities. Implementation
1500 assert(cs->multis == NULL); /* xxx */
1504 - mccase - add case counterparts of the list of collating elements in a cset
1505 == static void mccase(struct parse *p, cset *cs);
1507 * This would have to know the set of possibilities. Implementation
1515 assert(cs->multis == NULL); /* xxx */
1519 - isinsets - is this character in any sets?
1520 == static int isinsets(struct re_guts *g, int c);
1522 static int /* predicate */
1529 int ncols = (g->ncsets + (CHAR_BIT - 1)) / CHAR_BIT;
1530 unsigned uc = (unsigned char) c;
1532 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1539 - samesets - are these two characters in exactly the same sets?
1540 == static int samesets(struct re_guts *g, int c1, int c2);
1542 static int /* predicate */
1550 int ncols = (g->ncsets + (CHAR_BIT - 1)) / CHAR_BIT;
1551 unsigned uc1 = (unsigned char) c1;
1552 unsigned uc2 = (unsigned char) c2;
1554 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1555 if (col[uc1] != col[uc2])
1561 - categorize - sort out character categories
1562 == static void categorize(struct parse *p, struct re_guts *g);
1569 cat_t *cats = g->categories;
1574 /* avoid making error situations worse */
1578 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1579 if (cats[c] == 0 && isinsets(g, c))
1581 cat = g->ncategories++;
1583 for (c2 = c + 1; c2 <= CHAR_MAX; c2++)
1584 if (cats[c2] == 0 && samesets(g, c, c2))
1590 - dupl - emit a duplicate of a bunch of sops
1591 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1593 static sopno /* start of duplicate */
1594 dupl(p, start, finish)
1596 sopno start; /* from here */
1597 sopno finish; /* to this less one */
1600 sopno len = finish - start;
1602 assert(finish >= start);
1605 enlarge(p, p->ssize + len); /* this many unexpected additions */
1606 assert(p->ssize >= p->slen + len);
1607 memcpy((char *) (p->strip + p->slen),
1608 (char *) (p->strip + start), (size_t) len * sizeof(sop));
1614 - doemit - emit a strip operator
1615 == static void doemit(struct parse *p, sop op, size_t opnd);
1617 * It might seem better to implement this as a macro with a function as
1618 * hard-case backup, but it's just too big and messy unless there are
1619 * some changes to the data structures. Maybe later.
1627 /* avoid making error situations worse */
1631 /* deal with oversize operands ("can't happen", more or less) */
1632 assert(opnd < 1 << OPSHIFT);
1634 /* deal with undersized strip */
1635 if (p->slen >= p->ssize)
1636 enlarge(p, (p->ssize + 1) / 2 * 3); /* +50% */
1637 assert(p->slen < p->ssize);
1639 /* finally, it's all reduced to the easy case */
1640 p->strip[p->slen++] = SOP(op, opnd);
1644 - doinsert - insert a sop into the strip
1645 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1648 doinsert(p, op, opnd, pos)
1658 /* avoid making error situations worse */
1663 EMIT(op, opnd); /* do checks, ensure space */
1664 assert(HERE() == sn + 1);
1667 /* adjust paren pointers */
1669 for (i = 1; i < NPAREN; i++)
1671 if (p->pbegin[i] >= pos)
1673 if (p->pend[i] >= pos)
1677 memmove((char *) &p->strip[pos + 1], (char *) &p->strip[pos],
1678 (HERE() - pos - 1) * sizeof(sop));
1683 - dofwd - complete a forward reference
1684 == static void dofwd(struct parse *p, sopno pos, sop value);
1687 dofwd(p, pos, value)
1692 /* avoid making error situations worse */
1696 assert(value < 1 << OPSHIFT);
1697 p->strip[pos] = OP(p->strip[pos]) | value;
1701 - enlarge - enlarge the strip
1702 == static void enlarge(struct parse *p, sopno size);
1711 if (p->ssize >= size)
1714 sp = (sop *) realloc(p->strip, size * sizeof(sop));
1717 SETERROR(REG_ESPACE);
1725 - stripsnug - compact the strip
1726 == static void stripsnug(struct parse *p, struct re_guts *g);
1733 g->nstates = p->slen;
1734 g->strip = (sop *) realloc((char *) p->strip, p->slen * sizeof(sop));
1735 if (g->strip == NULL)
1737 SETERROR(REG_ESPACE);
1738 g->strip = p->strip;
1743 - findmust - fill in must and mlen with longest mandatory literal string
1744 == static void findmust(struct parse *p, struct re_guts *g);
1746 * This algorithm could do fancy things like analyzing the operands of |
1747 * for common subsequences. Someday. This code is simple and finds most
1748 * of the interesting cases.
1750 * Note that must and mlen got initialized during setup.
1765 /* avoid making error situations worse */
1769 /* find the longest OCHAR sequence in strip */
1771 scan = g->strip + 1;
1777 case OCHAR: /* sequence member */
1778 if (newlen == 0)/* new sequence */
1779 newstart = scan - 1;
1782 case OPLUS_: /* things that don't break one */
1786 case OQUEST_: /* things that must be skipped */
1793 /* assert() interferes w debug printouts */
1794 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1800 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1802 default: /* things that break a sequence */
1803 if (newlen > g->mlen)
1811 } while (OP(s) != OEND);
1813 if (g->mlen == 0) /* there isn't one */
1816 /* turn it into a character string */
1818 g->must = (pg_wchar *) malloc((size_t) (g->mlen + 1) * sizeof(pg_wchar));
1820 g->must = malloc((size_t) g->mlen + 1);
1822 if (g->must == NULL)
1823 { /* argh; just forget it */
1829 for (i = g->mlen; i > 0; i--)
1831 while (OP(s = *scan++) != OCHAR)
1833 assert(cp < g->must + g->mlen);
1834 *cp++ = (pg_wchar) OPND(s);
1836 assert(cp == g->must + g->mlen);
1837 *cp++ = '\0'; /* just on general principles */
1841 - pluscount - count + nesting
1842 == static sopno pluscount(struct parse *p, struct re_guts *g);
1844 static sopno /* nesting depth */
1855 return 0; /* there may not be an OEND */
1857 scan = g->strip + 1;
1867 if (plusnest > maxnest)
1872 } while (OP(s) != OEND);
1879 * some ctype functions with none-ascii-char guard
1885 return (c >= 0 && c <= UCHAR_MAX && isdigit(c));
1887 return (isdigit(c));
1895 return (c >= 0 && c <= UCHAR_MAX && isalpha(c));
1897 return (isalpha(c));
1905 return (c >= 0 && c <= UCHAR_MAX && isupper(c));
1907 return (isupper(c));
1915 return (c >= 0 && c <= UCHAR_MAX && islower(c));
1917 return (islower(c));