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
39 * $FreeBSD: src/lib/libc/regex/regcomp.c,v 1.13.2.2 2002/03/20 13:13:15 dcs Exp $
40 * $DragonFly: src/lib/libcr/regex/Attic/regcomp.c,v 1.3 2003/11/12 20:21:28 eirikn Exp $
42 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
45 #include <sys/types.h>
62 * parse structure, passed up and down to avoid global variables and
66 char *next; /* next character in RE */
67 char *end; /* end of string (-> NUL normally) */
68 int error; /* has an error been seen? */
69 sop *strip; /* malloced strip */
70 sopno ssize; /* malloced strip size (allocated) */
71 sopno slen; /* malloced strip length (used) */
72 int ncsalloc; /* number of csets allocated */
74 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
75 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
76 sopno pend[NPAREN]; /* -> ) ([0] unused) */
79 /* ========= begin header generated by ./mkh ========= */
84 /* === regcomp.c === */
85 static void p_ere (struct parse *p, int stop);
86 static void p_ere_exp (struct parse *p);
87 static void p_str (struct parse *p);
88 static void p_bre (struct parse *p, int end1, int end2);
89 static int p_simp_re (struct parse *p, int starordinary);
90 static int p_count (struct parse *p);
91 static void p_bracket (struct parse *p);
92 static void p_b_term (struct parse *p, cset *cs);
93 static void p_b_cclass (struct parse *p, cset *cs);
94 static void p_b_eclass (struct parse *p, cset *cs);
95 static char p_b_symbol (struct parse *p);
96 static char p_b_coll_elem (struct parse *p, int endc);
97 static char othercase (int ch);
98 static void bothcases (struct parse *p, int ch);
99 static void ordinary (struct parse *p, int ch);
100 static void nonnewline (struct parse *p);
101 static void repeat (struct parse *p, sopno start, int from, int to);
102 static int seterr (struct parse *p, int e);
103 static cset *allocset (struct parse *p);
104 static void freeset (struct parse *p, cset *cs);
105 static int freezeset (struct parse *p, cset *cs);
106 static int firstch (struct parse *p, cset *cs);
107 static int nch (struct parse *p, cset *cs);
108 static void mcadd (struct parse *p, cset *cs, char *cp);
110 static void mcsub (cset *cs, char *cp);
111 static int mcin (cset *cs, char *cp);
112 static char *mcfind (cset *cs, char *cp);
114 static void mcinvert (struct parse *p, cset *cs);
115 static void mccase (struct parse *p, cset *cs);
116 static int isinsets (struct re_guts *g, int c);
117 static int samesets (struct re_guts *g, int c1, int c2);
118 static void categorize (struct parse *p, struct re_guts *g);
119 static sopno dupl (struct parse *p, sopno start, sopno finish);
120 static void doemit (struct parse *p, sop op, size_t opnd);
121 static void doinsert (struct parse *p, sop op, size_t opnd, sopno pos);
122 static void dofwd (struct parse *p, sopno pos, sop value);
123 static void enlarge (struct parse *p, sopno size);
124 static void stripsnug (struct parse *p, struct re_guts *g);
125 static void findmust (struct parse *p, struct re_guts *g);
126 static int altoffset (sop *scan, int offset, int mccs);
127 static void computejumps (struct parse *p, struct re_guts *g);
128 static void computematchjumps (struct parse *p, struct re_guts *g);
129 static sopno pluscount (struct parse *p, struct re_guts *g);
134 /* ========= end header generated by ./mkh ========= */
136 static char nuls[10]; /* place to point scanner in event of error */
139 * macros for use with parse structure
140 * BEWARE: these know that the parse structure is named `p' !!!
142 #define PEEK() (*p->next)
143 #define PEEK2() (*(p->next+1))
144 #define MORE() (p->next < p->end)
145 #define MORE2() (p->next+1 < p->end)
146 #define SEE(c) (MORE() && PEEK() == (c))
147 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
148 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
149 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
150 #define NEXT() (p->next++)
151 #define NEXT2() (p->next += 2)
152 #define NEXTn(n) (p->next += (n))
153 #define GETNEXT() (*p->next++)
154 #define SETERROR(e) seterr(p, (e))
155 #define REQUIRE(co, e) ((co) || SETERROR(e))
156 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
157 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
158 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
159 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
160 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
161 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
162 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
163 #define HERE() (p->slen)
164 #define THERE() (p->slen - 1)
165 #define THERETHERE() (p->slen - 2)
166 #define DROP(n) (p->slen -= (n))
169 static int never = 0; /* for use in asserts; shuts lint up */
171 #define never 0 /* some <assert.h>s have bugs too */
174 /* Macro used by computejump()/computematchjump() */
175 #define MIN(a,b) ((a)<(b)?(a):(b))
178 - regcomp - interface for parser and compilation
179 = extern int regcomp(regex_t *, const char *, int);
180 = #define REG_BASIC 0000
181 = #define REG_EXTENDED 0001
182 = #define REG_ICASE 0002
183 = #define REG_NOSUB 0004
184 = #define REG_NEWLINE 0010
185 = #define REG_NOSPEC 0020
186 = #define REG_PEND 0040
187 = #define REG_DUMP 0200
189 int /* 0 success, otherwise REG_something */
190 regcomp(preg, pattern, cflags)
196 register struct re_guts *g;
197 register struct parse *p = &pa;
201 # define GOODFLAGS(f) (f)
203 # define GOODFLAGS(f) ((f)&~REG_DUMP)
206 cflags = GOODFLAGS(cflags);
207 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
210 if (cflags®_PEND) {
211 if (preg->re_endp < pattern)
213 len = preg->re_endp - pattern;
215 len = strlen((char *)pattern);
217 /* do the mallocs early so failure handling is easy */
218 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
219 (NC-1)*sizeof(cat_t));
222 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
223 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
225 if (p->strip == NULL) {
232 p->next = (char *)pattern; /* convenience; we do not modify it */
233 p->end = p->next + len;
236 for (i = 0; i < NPAREN; i++) {
254 g->ncategories = 1; /* category 0 is "everything else" */
255 g->categories = &g->catspace[-(CHAR_MIN)];
256 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
261 g->firststate = THERE();
262 if (cflags®_EXTENDED)
264 else if (cflags®_NOSPEC)
269 g->laststate = THERE();
271 /* tidy up loose ends and fill things in */
275 /* only use Boyer-Moore algorithm if the pattern is bigger
276 * than three characters
280 computematchjumps(p, g);
281 if(g->matchjump == NULL && g->charjump != NULL) {
286 g->nplus = pluscount(p, g);
288 preg->re_nsub = g->nsub;
290 preg->re_magic = MAGIC1;
292 /* not debugging, so can't rely on the assert() in regexec() */
294 SETERROR(REG_ASSERT);
297 /* win or lose, we're done */
298 if (p->error != 0) /* lose */
304 - p_ere - ERE parser top level, concatenation and alternation
305 == static void p_ere(register struct parse *p, int stop);
309 register struct parse *p;
310 int stop; /* character this ERE should end at */
313 register sopno prevback;
314 register sopno prevfwd;
316 register int first = 1; /* is this the first alternative? */
319 /* do a bunch of concatenated expressions */
321 while (MORE() && (c = PEEK()) != '|' && c != stop)
323 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
326 break; /* NOTE BREAK OUT */
329 INSERT(OCH_, conc); /* offset is wrong */
334 ASTERN(OOR1, prevback);
336 AHEAD(prevfwd); /* fix previous offset */
338 EMIT(OOR2, 0); /* offset is very wrong */
341 if (!first) { /* tail-end fixups */
343 ASTERN(O_CH, prevback);
346 assert(!MORE() || SEE(stop));
350 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
351 == static void p_ere_exp(register struct parse *p);
355 register struct parse *p;
361 register sopno subno;
364 assert(MORE()); /* caller should have ensured this */
370 (void)REQUIRE(MORE(), REG_EPAREN);
374 p->pbegin[subno] = HERE();
375 EMIT(OLPAREN, subno);
378 if (subno < NPAREN) {
379 p->pend[subno] = HERE();
380 assert(p->pend[subno] != 0);
382 EMIT(ORPAREN, subno);
383 (void)MUSTEAT(')', REG_EPAREN);
385 #ifndef POSIX_MISTAKE
386 case ')': /* happens only if no current unmatched ( */
388 * You may ask, why the ifndef? Because I didn't notice
389 * this until slightly too late for 1003.2, and none of the
390 * other 1003.2 regular-expression reviewers noticed it at
391 * all. So an unmatched ) is legal POSIX, at least until
392 * we can get it fixed.
394 SETERROR(REG_EPAREN);
399 p->g->iflags |= USEBOL;
405 p->g->iflags |= USEEOL;
414 SETERROR(REG_BADRPT);
417 if (p->g->cflags®_NEWLINE)
426 (void)REQUIRE(MORE(), REG_EESCAPE);
430 case '{': /* okay as ordinary except if digit follows */
431 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
441 /* we call { a repetition if followed by a digit */
442 if (!( c == '*' || c == '+' || c == '?' ||
443 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
444 return; /* no repetition, we're done */
447 (void)REQUIRE(!wascaret, REG_BADRPT);
449 case '*': /* implemented as +? */
450 /* this case does not require the (y|) trick, noKLUDGE */
453 INSERT(OQUEST_, pos);
454 ASTERN(O_QUEST, pos);
461 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
462 INSERT(OCH_, pos); /* offset slightly wrong */
463 ASTERN(OOR1, pos); /* this one's right */
464 AHEAD(pos); /* fix the OCH_ */
465 EMIT(OOR2, 0); /* offset very wrong... */
466 AHEAD(THERE()); /* ...so fix it */
467 ASTERN(O_CH, THERETHERE());
472 if (isdigit((uch)PEEK())) {
474 (void)REQUIRE(count <= count2, REG_BADBR);
475 } else /* single number with comma */
477 } else /* just a single number */
479 repeat(p, pos, count, count2);
480 if (!EAT('}')) { /* error heuristics */
481 while (MORE() && PEEK() != '}')
483 (void)REQUIRE(MORE(), REG_EBRACE);
492 if (!( c == '*' || c == '+' || c == '?' ||
493 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
495 SETERROR(REG_BADRPT);
499 - p_str - string (no metacharacters) "parser"
500 == static void p_str(register struct parse *p);
504 register struct parse *p;
506 (void)REQUIRE(MORE(), REG_EMPTY);
508 ordinary(p, GETNEXT());
512 - p_bre - BRE parser top level, anchoring and concatenation
513 == static void p_bre(register struct parse *p, register int end1, \
514 == register int end2);
515 * Giving end1 as OUT essentially eliminates the end1/end2 check.
517 * This implementation is a bit of a kludge, in that a trailing $ is first
518 * taken as an ordinary character and then revised to be an anchor. The
519 * only undesirable side effect is that '$' gets included as a character
520 * category in such cases. This is fairly harmless; not worth fixing.
521 * The amount of lookahead needed to avoid this kludge is excessive.
525 register struct parse *p;
526 register int end1; /* first terminating character */
527 register int end2; /* second terminating character */
529 register sopno start = HERE();
530 register int first = 1; /* first subexpression? */
531 register int wasdollar = 0;
535 p->g->iflags |= USEBOL;
538 while (MORE() && !SEETWO(end1, end2)) {
539 wasdollar = p_simp_re(p, first);
542 if (wasdollar) { /* oops, that was a trailing anchor */
545 p->g->iflags |= USEEOL;
549 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
553 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
554 == static int p_simp_re(register struct parse *p, int starordinary);
556 static int /* was the simple RE an unbackslashed $? */
557 p_simp_re(p, starordinary)
558 register struct parse *p;
559 int starordinary; /* is a leading * an ordinary character? */
566 register sopno subno;
567 # define BACKSL (1<<CHAR_BIT)
569 pos = HERE(); /* repetion op, if any, covers from here */
571 assert(MORE()); /* caller should have ensured this */
574 (void)REQUIRE(MORE(), REG_EESCAPE);
575 c = BACKSL | GETNEXT();
579 if (p->g->cflags®_NEWLINE)
588 SETERROR(REG_BADRPT);
594 p->pbegin[subno] = HERE();
595 EMIT(OLPAREN, subno);
596 /* the MORE here is an error heuristic */
597 if (MORE() && !SEETWO('\\', ')'))
599 if (subno < NPAREN) {
600 p->pend[subno] = HERE();
601 assert(p->pend[subno] != 0);
603 EMIT(ORPAREN, subno);
604 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
606 case BACKSL|')': /* should not get here -- must be user */
608 SETERROR(REG_EPAREN);
619 i = (c&~BACKSL) - '0';
621 if (p->pend[i] != 0) {
622 assert(i <= p->g->nsub);
624 assert(p->pbegin[i] != 0);
625 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
626 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
627 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
630 SETERROR(REG_ESUBREG);
634 (void)REQUIRE(starordinary, REG_BADRPT);
637 ordinary(p, (char)c);
641 if (EAT('*')) { /* implemented as +? */
642 /* this case does not require the (y|) trick, noKLUDGE */
645 INSERT(OQUEST_, pos);
646 ASTERN(O_QUEST, pos);
647 } else if (EATTWO('\\', '{')) {
650 if (MORE() && isdigit((uch)PEEK())) {
652 (void)REQUIRE(count <= count2, REG_BADBR);
653 } else /* single number with comma */
655 } else /* just a single number */
657 repeat(p, pos, count, count2);
658 if (!EATTWO('\\', '}')) { /* error heuristics */
659 while (MORE() && !SEETWO('\\', '}'))
661 (void)REQUIRE(MORE(), REG_EBRACE);
664 } else if (c == '$') /* $ (but not \$) ends it */
671 - p_count - parse a repetition count
672 == static int p_count(register struct parse *p);
674 static int /* the value */
676 register struct parse *p;
678 register int count = 0;
679 register int ndigits = 0;
681 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
682 count = count*10 + (GETNEXT() - '0');
686 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
691 - p_bracket - parse a bracketed character list
692 == static void p_bracket(register struct parse *p);
694 * Note a significant property of this code: if the allocset() did SETERROR,
695 * no set operations are done.
699 register struct parse *p;
701 register cset *cs = allocset(p);
702 register int invert = 0;
704 /* Dept of Truly Sickening Special-Case Kludges */
705 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
710 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
717 invert++; /* make note to invert set at end */
722 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
726 (void)MUSTEAT(']', REG_EBRACK);
728 if (p->error != 0) /* don't mess things up further */
731 if (p->g->cflags®_ICASE) {
735 for (i = p->g->csetsize - 1; i >= 0; i--)
736 if (CHIN(cs, i) && isalpha(i)) {
741 if (cs->multis != NULL)
747 for (i = p->g->csetsize - 1; i >= 0; i--)
752 if (p->g->cflags®_NEWLINE)
754 if (cs->multis != NULL)
758 assert(cs->multis == NULL); /* xxx */
760 if (nch(p, cs) == 1) { /* optimize singleton sets */
761 ordinary(p, firstch(p, cs));
764 EMIT(OANYOF, freezeset(p, cs));
768 - p_b_term - parse one term of a bracketed character list
769 == static void p_b_term(register struct parse *p, register cset *cs);
773 register struct parse *p;
777 register char start, finish;
780 /* classify what we've got */
781 switch ((MORE()) ? PEEK() : '\0') {
783 c = (MORE2()) ? PEEK2() : '\0';
786 SETERROR(REG_ERANGE);
787 return; /* NOTE RETURN */
795 case ':': /* character class */
797 (void)REQUIRE(MORE(), REG_EBRACK);
799 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
801 (void)REQUIRE(MORE(), REG_EBRACK);
802 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
804 case '=': /* equivalence class */
806 (void)REQUIRE(MORE(), REG_EBRACK);
808 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
810 (void)REQUIRE(MORE(), REG_EBRACK);
811 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
813 default: /* symbol, ordinary character, or range */
814 /* xxx revision needed for multichar stuff */
815 start = p_b_symbol(p);
816 if (SEE('-') && MORE2() && PEEK2() != ']') {
822 finish = p_b_symbol(p);
828 if (__collate_load_error) {
829 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
830 for (i = (uch)start; i <= (uch)finish; i++)
833 (void)REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE);
834 for (i = CHAR_MIN; i <= CHAR_MAX; i++) {
835 if ( __collate_range_cmp(start, i) <= 0
836 && __collate_range_cmp(i, finish) <= 0
847 - p_b_cclass - parse a character-class name and deal with it
848 == static void p_b_cclass(register struct parse *p, register cset *cs);
852 register struct parse *p;
856 register char *sp = p->next;
857 register struct cclass *cp;
860 while (MORE() && isalpha((uch)PEEK()))
863 for (cp = cclasses; cp->name != NULL; cp++)
864 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
866 if (cp->name == NULL) {
867 /* oops, didn't find it */
868 SETERROR(REG_ECTYPE);
874 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
879 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
884 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
889 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
894 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
899 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
904 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
909 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
914 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
919 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
924 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
929 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
930 if (isxdigit((uch)c))
935 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
941 - p_b_eclass - parse an equivalence-class name and deal with it
942 == static void p_b_eclass(register struct parse *p, register cset *cs);
944 * This implementation is incomplete. xxx
948 register struct parse *p;
953 c = p_b_coll_elem(p, '=');
958 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
959 == static char p_b_symbol(register struct parse *p);
961 static char /* value of symbol */
963 register struct parse *p;
967 (void)REQUIRE(MORE(), REG_EBRACK);
968 if (!EATTWO('[', '.'))
971 /* collating symbol */
972 value = p_b_coll_elem(p, '.');
973 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
978 - p_b_coll_elem - parse a collating-element name and look it up
979 == static char p_b_coll_elem(register struct parse *p, int endc);
981 static char /* value of collating element */
982 p_b_coll_elem(p, endc)
983 register struct parse *p;
984 int endc; /* name ended by endc,']' */
986 register char *sp = p->next;
987 register struct cname *cp;
990 while (MORE() && !SEETWO(endc, ']'))
993 SETERROR(REG_EBRACK);
997 for (cp = cnames; cp->name != NULL; cp++)
998 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
999 return(cp->code); /* known name */
1001 return(*sp); /* single character */
1002 SETERROR(REG_ECOLLATE); /* neither */
1007 - othercase - return the case counterpart of an alphabetic
1008 == static char othercase(int ch);
1010 static char /* if no counterpart, return ch */
1015 assert(isalpha(ch));
1017 return(tolower(ch));
1018 else if (islower(ch))
1019 return(toupper(ch));
1020 else /* peculiar, but could happen */
1025 - bothcases - emit a dualcase version of a two-case character
1026 == static void bothcases(register struct parse *p, int ch);
1028 * Boy, is this implementation ever a kludge...
1032 register struct parse *p;
1035 register char *oldnext = p->next;
1036 register char *oldend = p->end;
1040 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1047 assert(p->next == bracket+2);
1053 - ordinary - emit an ordinary character
1054 == static void ordinary(register struct parse *p, register int ch);
1058 register struct parse *p;
1061 register cat_t *cap = p->g->categories;
1063 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
1066 EMIT(OCHAR, (uch)ch);
1068 cap[ch] = p->g->ncategories++;
1073 - nonnewline - emit REG_NEWLINE version of OANY
1074 == static void nonnewline(register struct parse *p);
1076 * Boy, is this implementation ever a kludge...
1080 register struct parse *p;
1082 register char *oldnext = p->next;
1083 register char *oldend = p->end;
1093 assert(p->next == bracket+3);
1099 - repeat - generate code for a bounded repetition, recursively if needed
1100 == static void repeat(register struct parse *p, sopno start, int from, int to);
1103 repeat(p, start, from, to)
1104 register struct parse *p;
1105 sopno start; /* operand from here to end of strip */
1106 int from; /* repeated from this number */
1107 int to; /* to this number of times (maybe INFINITY) */
1109 register sopno finish = HERE();
1112 # define REP(f, t) ((f)*8 + (t))
1113 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1114 register sopno copy;
1116 if (p->error != 0) /* head off possible runaway recursion */
1121 switch (REP(MAP(from), MAP(to))) {
1122 case REP(0, 0): /* must be user doing this */
1123 DROP(finish-start); /* drop the operand */
1125 case REP(0, 1): /* as x{1,1}? */
1126 case REP(0, N): /* as x{1,n}? */
1127 case REP(0, INF): /* as x{1,}? */
1128 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1129 INSERT(OCH_, start); /* offset is wrong... */
1130 repeat(p, start+1, 1, to);
1131 ASTERN(OOR1, start);
1132 AHEAD(start); /* ... fix it */
1135 ASTERN(O_CH, THERETHERE());
1137 case REP(1, 1): /* trivial case */
1140 case REP(1, N): /* as x?x{1,n-1} */
1141 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1142 INSERT(OCH_, start);
1143 ASTERN(OOR1, start);
1145 EMIT(OOR2, 0); /* offset very wrong... */
1146 AHEAD(THERE()); /* ...so fix it */
1147 ASTERN(O_CH, THERETHERE());
1148 copy = dupl(p, start+1, finish+1);
1149 assert(copy == finish+4);
1150 repeat(p, copy, 1, to-1);
1152 case REP(1, INF): /* as x+ */
1153 INSERT(OPLUS_, start);
1154 ASTERN(O_PLUS, start);
1156 case REP(N, N): /* as xx{m-1,n-1} */
1157 copy = dupl(p, start, finish);
1158 repeat(p, copy, from-1, to-1);
1160 case REP(N, INF): /* as xx{n-1,INF} */
1161 copy = dupl(p, start, finish);
1162 repeat(p, copy, from-1, to);
1164 default: /* "can't happen" */
1165 SETERROR(REG_ASSERT); /* just in case */
1171 - seterr - set an error condition
1172 == static int seterr(register struct parse *p, int e);
1174 static int /* useless but makes type checking happy */
1176 register struct parse *p;
1179 if (p->error == 0) /* keep earliest error condition */
1181 p->next = nuls; /* try to bring things to a halt */
1183 return(0); /* make the return value well-defined */
1187 - allocset - allocate a set of characters for []
1188 == static cset *allocset(register struct parse *p);
1192 register struct parse *p;
1194 register int no = p->g->ncsets++;
1196 register size_t nbytes;
1198 register size_t css = (size_t)p->g->csetsize;
1201 if (no >= p->ncsalloc) { /* need another column of space */
1202 p->ncsalloc += CHAR_BIT;
1204 assert(nc % CHAR_BIT == 0);
1205 nbytes = nc / CHAR_BIT * css;
1206 if (p->g->sets == NULL)
1207 p->g->sets = (cset *)malloc(nc * sizeof(cset));
1209 p->g->sets = (cset *)reallocf((char *)p->g->sets,
1211 if (p->g->setbits == NULL)
1212 p->g->setbits = (uch *)malloc(nbytes);
1214 p->g->setbits = (uch *)reallocf((char *)p->g->setbits,
1216 /* xxx this isn't right if setbits is now NULL */
1217 for (i = 0; i < no; i++)
1218 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1220 if (p->g->sets != NULL && p->g->setbits != NULL)
1221 (void) memset((char *)p->g->setbits + (nbytes - css),
1225 SETERROR(REG_ESPACE);
1226 /* caller's responsibility not to do set ops */
1230 assert(p->g->sets != NULL); /* xxx */
1231 cs = &p->g->sets[no];
1232 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1233 cs->mask = 1 << ((no) % CHAR_BIT);
1242 - freeset - free a now-unused set
1243 == static void freeset(register struct parse *p, register cset *cs);
1247 register struct parse *p;
1251 register cset *top = &p->g->sets[p->g->ncsets];
1252 register size_t css = (size_t)p->g->csetsize;
1254 for (i = 0; i < css; i++)
1256 if (cs == top-1) /* recover only the easy case */
1261 - freezeset - final processing on a set of characters
1262 == static int freezeset(register struct parse *p, register cset *cs);
1264 * The main task here is merging identical sets. This is usually a waste
1265 * of time (although the hash code minimizes the overhead), but can win
1266 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1267 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1270 static int /* set number */
1272 register struct parse *p;
1275 register short h = cs->hash;
1277 register cset *top = &p->g->sets[p->g->ncsets];
1279 register size_t css = (size_t)p->g->csetsize;
1281 /* look for an earlier one which is the same */
1282 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1283 if (cs2->hash == h && cs2 != cs) {
1285 for (i = 0; i < css; i++)
1286 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1292 if (cs2 < top) { /* found one */
1297 return((int)(cs - p->g->sets));
1301 - firstch - return first character in a set (which must have at least one)
1302 == static int firstch(register struct parse *p, register cset *cs);
1304 static int /* character; there is no "none" value */
1306 register struct parse *p;
1310 register size_t css = (size_t)p->g->csetsize;
1312 for (i = 0; i < css; i++)
1316 return(0); /* arbitrary */
1320 - nch - number of characters in a set
1321 == static int nch(register struct parse *p, register cset *cs);
1325 register struct parse *p;
1329 register size_t css = (size_t)p->g->csetsize;
1332 for (i = 0; i < css; i++)
1339 - mcadd - add a collating element to a cset
1340 == static void mcadd(register struct parse *p, register cset *cs, \
1341 == register char *cp);
1345 register struct parse *p;
1349 register size_t oldend = cs->smultis;
1351 cs->smultis += strlen(cp) + 1;
1352 if (cs->multis == NULL)
1353 cs->multis = malloc(cs->smultis);
1355 cs->multis = reallocf(cs->multis, cs->smultis);
1356 if (cs->multis == NULL) {
1357 SETERROR(REG_ESPACE);
1361 (void) strcpy(cs->multis + oldend - 1, cp);
1362 cs->multis[cs->smultis - 1] = '\0';
1367 - mcsub - subtract a collating element from a cset
1368 == static void mcsub(register cset *cs, register char *cp);
1375 register char *fp = mcfind(cs, cp);
1376 register size_t len = strlen(fp);
1379 (void) memmove(fp, fp + len + 1,
1380 cs->smultis - (fp + len + 1 - cs->multis));
1383 if (cs->smultis == 0) {
1389 cs->multis = reallocf(cs->multis, cs->smultis);
1390 assert(cs->multis != NULL);
1394 - mcin - is a collating element in a cset?
1395 == static int mcin(register cset *cs, register char *cp);
1402 return(mcfind(cs, cp) != NULL);
1406 - mcfind - find a collating element in a cset
1407 == static char *mcfind(register cset *cs, register char *cp);
1416 if (cs->multis == NULL)
1418 for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
1419 if (strcmp(cp, p) == 0)
1426 - mcinvert - invert the list of collating elements in a cset
1427 == static void mcinvert(register struct parse *p, register cset *cs);
1429 * This would have to know the set of possibilities. Implementation
1434 register struct parse *p;
1437 assert(cs->multis == NULL); /* xxx */
1441 - mccase - add case counterparts of the list of collating elements in a cset
1442 == static void mccase(register struct parse *p, register cset *cs);
1444 * This would have to know the set of possibilities. Implementation
1449 register struct parse *p;
1452 assert(cs->multis == NULL); /* xxx */
1456 - isinsets - is this character in any sets?
1457 == static int isinsets(register struct re_guts *g, int c);
1459 static int /* predicate */
1461 register struct re_guts *g;
1466 register int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1467 register unsigned uc = (uch)c;
1469 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1476 - samesets - are these two characters in exactly the same sets?
1477 == static int samesets(register struct re_guts *g, int c1, int c2);
1479 static int /* predicate */
1481 register struct re_guts *g;
1487 register int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1488 register unsigned uc1 = (uch)c1;
1489 register unsigned uc2 = (uch)c2;
1491 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1492 if (col[uc1] != col[uc2])
1498 - categorize - sort out character categories
1499 == static void categorize(struct parse *p, register struct re_guts *g);
1504 register struct re_guts *g;
1506 register cat_t *cats = g->categories;
1511 /* avoid making error situations worse */
1515 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1516 if (cats[c] == 0 && isinsets(g, c)) {
1517 cat = g->ncategories++;
1519 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1520 if (cats[c2] == 0 && samesets(g, c, c2))
1526 - dupl - emit a duplicate of a bunch of sops
1527 == static sopno dupl(register struct parse *p, sopno start, sopno finish);
1529 static sopno /* start of duplicate */
1530 dupl(p, start, finish)
1531 register struct parse *p;
1532 sopno start; /* from here */
1533 sopno finish; /* to this less one */
1535 register sopno ret = HERE();
1536 register sopno len = finish - start;
1538 assert(finish >= start);
1541 enlarge(p, p->ssize + len); /* this many unexpected additions */
1542 assert(p->ssize >= p->slen + len);
1543 (void) memcpy((char *)(p->strip + p->slen),
1544 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1550 - doemit - emit a strip operator
1551 == static void doemit(register struct parse *p, sop op, size_t opnd);
1553 * It might seem better to implement this as a macro with a function as
1554 * hard-case backup, but it's just too big and messy unless there are
1555 * some changes to the data structures. Maybe later.
1559 register struct parse *p;
1563 /* avoid making error situations worse */
1567 /* deal with oversize operands ("can't happen", more or less) */
1568 assert(opnd < 1<<OPSHIFT);
1570 /* deal with undersized strip */
1571 if (p->slen >= p->ssize)
1572 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1573 assert(p->slen < p->ssize);
1575 /* finally, it's all reduced to the easy case */
1576 p->strip[p->slen++] = SOP(op, opnd);
1580 - doinsert - insert a sop into the strip
1581 == static void doinsert(register struct parse *p, sop op, size_t opnd, sopno pos);
1584 doinsert(p, op, opnd, pos)
1585 register struct parse *p;
1594 /* avoid making error situations worse */
1599 EMIT(op, opnd); /* do checks, ensure space */
1600 assert(HERE() == sn+1);
1603 /* adjust paren pointers */
1605 for (i = 1; i < NPAREN; i++) {
1606 if (p->pbegin[i] >= pos) {
1609 if (p->pend[i] >= pos) {
1614 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1615 (HERE()-pos-1)*sizeof(sop));
1620 - dofwd - complete a forward reference
1621 == static void dofwd(register struct parse *p, sopno pos, sop value);
1624 dofwd(p, pos, value)
1625 register struct parse *p;
1629 /* avoid making error situations worse */
1633 assert(value < 1<<OPSHIFT);
1634 p->strip[pos] = OP(p->strip[pos]) | value;
1638 - enlarge - enlarge the strip
1639 == static void enlarge(register struct parse *p, sopno size);
1643 register struct parse *p;
1644 register sopno size;
1648 if (p->ssize >= size)
1651 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1653 SETERROR(REG_ESPACE);
1661 - stripsnug - compact the strip
1662 == static void stripsnug(register struct parse *p, register struct re_guts *g);
1666 register struct parse *p;
1667 register struct re_guts *g;
1669 g->nstates = p->slen;
1670 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1671 if (g->strip == NULL) {
1672 SETERROR(REG_ESPACE);
1673 g->strip = p->strip;
1678 - findmust - fill in must and mlen with longest mandatory literal string
1679 == static void findmust(register struct parse *p, register struct re_guts *g);
1681 * This algorithm could do fancy things like analyzing the operands of |
1682 * for common subsequences. Someday. This code is simple and finds most
1683 * of the interesting cases.
1685 * Note that must and mlen got initialized during setup.
1690 register struct re_guts *g;
1694 register sop *newstart;
1695 register sopno newlen;
1702 /* avoid making error situations worse */
1706 /* Find out if we can handle OANYOF or not */
1708 for (cs = 0; cs < g->ncsets; cs++)
1709 if (g->sets[cs].multis != NULL)
1712 /* find the longest OCHAR sequence in strip */
1716 scan = g->strip + 1;
1720 case OCHAR: /* sequence member */
1721 if (newlen == 0) /* new sequence */
1722 newstart = scan - 1;
1725 case OPLUS_: /* things that don't break one */
1729 case OQUEST_: /* things that must be skipped */
1731 offset = altoffset(scan, offset, mccs);
1736 /* assert() interferes w debug printouts */
1737 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1742 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1744 case OBOW: /* things that break a sequence */
1751 if (newlen > g->mlen) { /* ends one */
1755 g->moffset += offset;
1758 g->moffset = offset;
1766 if (newlen > g->mlen) { /* ends one */
1770 g->moffset += offset;
1773 g->moffset = offset;
1782 case OANYOF: /* may or may not invalidate offset */
1783 /* First, everything as OANY */
1784 if (newlen > g->mlen) { /* ends one */
1788 g->moffset += offset;
1791 g->moffset = offset;
1799 /* And, now, if we found out we can't deal with
1800 * it, make offset = -1.
1806 /* Anything here makes it impossible or too hard
1807 * to calculate the offset -- so we give up;
1808 * save the last known good offset, in case the
1809 * must sequence doesn't occur later.
1811 if (newlen > g->mlen) { /* ends one */
1815 g->moffset += offset;
1817 g->moffset = offset;
1823 } while (OP(s) != OEND);
1825 if (g->mlen == 0) { /* there isn't one */
1830 /* turn it into a character string */
1831 g->must = malloc((size_t)g->mlen + 1);
1832 if (g->must == NULL) { /* argh; just forget it */
1839 for (i = g->mlen; i > 0; i--) {
1840 while (OP(s = *scan++) != OCHAR)
1842 assert(cp < g->must + g->mlen);
1843 *cp++ = (char)OPND(s);
1845 assert(cp == g->must + g->mlen);
1846 *cp++ = '\0'; /* just on general principles */
1850 - altoffset - choose biggest offset among multiple choices
1851 == static int altoffset(sop *scan, int offset, int mccs);
1853 * Compute, recursively if necessary, the largest offset among multiple
1857 altoffset(scan, offset, mccs)
1866 /* If we gave up already on offsets, return */
1873 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1882 try = altoffset(scan, try, mccs);
1889 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1892 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1893 /* We must skip to the next position, or we'll
1894 * leave altoffset() too early.
1922 return largest+offset;
1926 - computejumps - compute char jumps for BM scan
1927 == static void computejumps(register struct parse *p, register struct re_guts *g);
1929 * This algorithm assumes g->must exists and is has size greater than
1930 * zero. It's based on the algorithm found on Computer Algorithms by
1933 * A char jump is the number of characters one needs to jump based on
1934 * the value of the character from the text that was mismatched.
1944 /* Avoid making errors worse */
1948 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1949 if (g->charjump == NULL) /* Not a fatal error */
1951 /* Adjust for signed chars, if necessary */
1952 g->charjump = &g->charjump[-(CHAR_MIN)];
1954 /* If the character does not exist in the pattern, the jump
1955 * is equal to the number of characters in the pattern.
1957 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1958 g->charjump[ch] = g->mlen;
1960 /* If the character does exist, compute the jump that would
1961 * take us to the last character in the pattern equal to it
1962 * (notice that we match right to left, so that last character
1963 * is the first one that would be matched).
1965 for (mindex = 0; mindex < g->mlen; mindex++)
1966 g->charjump[g->must[mindex]] = g->mlen - mindex - 1;
1970 - computematchjumps - compute match jumps for BM scan
1971 == static void computematchjumps(register struct parse *p, register struct re_guts *g);
1973 * This algorithm assumes g->must exists and is has size greater than
1974 * zero. It's based on the algorithm found on Computer Algorithms by
1977 * A match jump is the number of characters one needs to advance based
1978 * on the already-matched suffix.
1979 * Notice that all values here are minus (g->mlen-1), because of the way
1980 * the search algorithm works.
1983 computematchjumps(p, g)
1987 int mindex; /* General "must" iterator */
1988 int suffix; /* Keeps track of matching suffix */
1989 int ssuffix; /* Keeps track of suffixes' suffix */
1990 int* pmatches; /* pmatches[k] points to the next i
1991 * such that i+1...mlen is a substring
1992 * of k+1...k+mlen-i-1
1995 /* Avoid making errors worse */
1999 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
2000 if (pmatches == NULL) {
2001 g->matchjump = NULL;
2005 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
2006 if (g->matchjump == NULL) /* Not a fatal error */
2009 /* Set maximum possible jump for each character in the pattern */
2010 for (mindex = 0; mindex < g->mlen; mindex++)
2011 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
2013 /* Compute pmatches[] */
2014 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
2015 mindex--, suffix--) {
2016 pmatches[mindex] = suffix;
2018 /* If a mismatch is found, interrupting the substring,
2019 * compute the matchjump for that position. If no
2020 * mismatch is found, then a text substring mismatched
2021 * against the suffix will also mismatch against the
2024 while (suffix < g->mlen
2025 && g->must[mindex] != g->must[suffix]) {
2026 g->matchjump[suffix] = MIN(g->matchjump[suffix],
2027 g->mlen - mindex - 1);
2028 suffix = pmatches[suffix];
2032 /* Compute the matchjump up to the last substring found to jump
2033 * to the beginning of the largest must pattern prefix matching
2036 for (mindex = 0; mindex <= suffix; mindex++)
2037 g->matchjump[mindex] = MIN(g->matchjump[mindex],
2038 g->mlen + suffix - mindex);
2040 ssuffix = pmatches[suffix];
2041 while (suffix < g->mlen) {
2042 while (suffix <= ssuffix && suffix < g->mlen) {
2043 g->matchjump[suffix] = MIN(g->matchjump[suffix],
2044 g->mlen + ssuffix - suffix);
2047 if (suffix < g->mlen)
2048 ssuffix = pmatches[ssuffix];
2055 - pluscount - count + nesting
2056 == static sopno pluscount(register struct parse *p, register struct re_guts *g);
2058 static sopno /* nesting depth */
2061 register struct re_guts *g;
2065 register sopno plusnest = 0;
2066 register sopno maxnest = 0;
2069 return(0); /* there may not be an OEND */
2071 scan = g->strip + 1;
2079 if (plusnest > maxnest)
2084 } while (OP(s) != OEND);