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 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
34 * $FreeBSD: src/lib/libc/regex/regcomp.c,v 1.36 2007/06/11 03:05:54 delphij Exp $
35 * $DragonFly: src/lib/libc/regex/regcomp.c,v 1.7 2005/11/20 09:18:37 swildner Exp $
38 #include <sys/types.h>
57 * parse structure, passed up and down to avoid global variables and
61 char *next; /* next character in RE */
62 char *end; /* end of string (-> NUL normally) */
63 int error; /* has an error been seen? */
64 sop *strip; /* malloced strip */
65 sopno ssize; /* malloced strip size (allocated) */
66 sopno slen; /* malloced strip length (used) */
67 int ncsalloc; /* number of csets allocated */
69 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
70 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
71 sopno pend[NPAREN]; /* -> ) ([0] unused) */
74 /* ========= begin header generated by ./mkh ========= */
79 /* === regcomp.c === */
80 static void p_ere(struct parse *p, wint_t stop);
81 static void p_ere_exp(struct parse *p);
82 static void p_str(struct parse *p);
83 static void p_bre(struct parse *p, wint_t end1, wint_t end2);
84 static int p_simp_re(struct parse *p, int starordinary);
85 static int p_count(struct parse *p);
86 static void p_bracket(struct parse *p);
87 static void p_b_term(struct parse *p, cset *cs);
88 static void p_b_cclass(struct parse *p, cset *cs);
89 static void p_b_eclass(struct parse *p, cset *cs);
90 static wint_t p_b_symbol(struct parse *p);
91 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
92 static wint_t othercase(wint_t ch);
93 static void bothcases(struct parse *p, wint_t ch);
94 static void ordinary(struct parse *p, wint_t ch);
95 static void nonnewline(struct parse *p);
96 static void repeat(struct parse *p, sopno start, int from, int to);
97 static int seterr(struct parse *p, int e);
98 static cset *allocset(struct parse *p);
99 static void freeset(struct parse *p, cset *cs);
100 static void CHadd(struct parse *p, cset *cs, wint_t ch);
101 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
102 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
103 static wint_t singleton(cset *cs);
104 static sopno dupl(struct parse *p, sopno start, sopno finish);
105 static void doemit(struct parse *p, sop op, size_t opnd);
106 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
107 static void dofwd(struct parse *p, sopno pos, sop value);
108 static void enlarge(struct parse *p, sopno size);
109 static void stripsnug(struct parse *p, struct re_guts *g);
110 static void findmust(struct parse *p, struct re_guts *g);
111 static int altoffset(sop *scan, int offset);
112 static void computejumps(struct parse *p, struct re_guts *g);
113 static void computematchjumps(struct parse *p, struct re_guts *g);
114 static sopno pluscount(struct parse *p, struct re_guts *g);
115 static wint_t wgetnext(struct parse *p);
120 /* ========= end header generated by ./mkh ========= */
122 static char nuls[10]; /* place to point scanner in event of error */
125 * macros for use with parse structure
126 * BEWARE: these know that the parse structure is named `p' !!!
128 #define PEEK() (*p->next)
129 #define PEEK2() (*(p->next+1))
130 #define MORE() (p->next < p->end)
131 #define MORE2() (p->next+1 < p->end)
132 #define SEE(c) (MORE() && PEEK() == (c))
133 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
134 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
135 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
136 #define NEXT() (p->next++)
137 #define NEXT2() (p->next += 2)
138 #define NEXTn(n) (p->next += (n))
139 #define GETNEXT() (*p->next++)
140 #define WGETNEXT() wgetnext(p)
141 #define SETERROR(e) seterr(p, (e))
142 #define REQUIRE(co, e) ((co) || SETERROR(e))
143 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
144 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
145 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
146 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
147 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
148 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
149 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
150 #define HERE() (p->slen)
151 #define THERE() (p->slen - 1)
152 #define THERETHERE() (p->slen - 2)
153 #define DROP(n) (p->slen -= (n))
156 static int never = 0; /* for use in asserts; shuts lint up */
158 #define never 0 /* some <assert.h>s have bugs too */
161 /* Macro used by computejump()/computematchjump() */
162 #define MIN(a,b) ((a)<(b)?(a):(b))
165 - regcomp - interface for parser and compilation
166 = extern int regcomp(regex_t *, const char *, int);
167 = #define REG_BASIC 0000
168 = #define REG_EXTENDED 0001
169 = #define REG_ICASE 0002
170 = #define REG_NOSUB 0004
171 = #define REG_NEWLINE 0010
172 = #define REG_NOSPEC 0020
173 = #define REG_PEND 0040
174 = #define REG_DUMP 0200
176 int /* 0 success, otherwise REG_something */
177 regcomp(regex_t * __restrict preg,
178 const char * __restrict pattern,
183 struct parse *p = &pa;
187 # define GOODFLAGS(f) (f)
189 # define GOODFLAGS(f) ((f)&~REG_DUMP)
192 cflags = GOODFLAGS(cflags);
193 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
196 if (cflags®_PEND) {
197 if (preg->re_endp < pattern)
199 len = preg->re_endp - pattern;
201 len = strlen((char *)pattern);
203 /* do the mallocs early so failure handling is easy */
204 g = (struct re_guts *)malloc(sizeof(struct re_guts));
207 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
208 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
210 if (p->strip == NULL) {
217 p->next = (char *)pattern; /* convenience; we do not modify it */
218 p->end = p->next + len;
221 for (i = 0; i < NPAREN; i++) {
241 g->firststate = THERE();
242 if (cflags®_EXTENDED)
244 else if (cflags®_NOSPEC)
249 g->laststate = THERE();
251 /* tidy up loose ends and fill things in */
254 /* only use Boyer-Moore algorithm if the pattern is bigger
255 * than three characters
259 computematchjumps(p, g);
260 if(g->matchjump == NULL && g->charjump != NULL) {
265 g->nplus = pluscount(p, g);
267 preg->re_nsub = g->nsub;
269 preg->re_magic = MAGIC1;
271 /* not debugging, so can't rely on the assert() in regexec() */
273 SETERROR(REG_ASSERT);
276 /* win or lose, we're done */
277 if (p->error != 0) /* lose */
283 - p_ere - ERE parser top level, concatenation and alternation
284 == static void p_ere(struct parse *p, int stop);
287 p_ere(struct parse *p,
288 int stop) /* character this ERE should end at */
294 int first = 1; /* is this the first alternative? */
297 /* do a bunch of concatenated expressions */
299 while (MORE() && (c = PEEK()) != '|' && c != stop)
301 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
304 break; /* NOTE BREAK OUT */
307 INSERT(OCH_, conc); /* offset is wrong */
312 ASTERN(OOR1, prevback);
314 AHEAD(prevfwd); /* fix previous offset */
316 EMIT(OOR2, 0); /* offset is very wrong */
319 if (!first) { /* tail-end fixups */
321 ASTERN(O_CH, prevback);
324 assert(!MORE() || SEE(stop));
328 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
329 == static void p_ere_exp(struct parse *p);
332 p_ere_exp(struct parse *p)
342 assert(MORE()); /* caller should have ensured this */
348 REQUIRE(MORE(), REG_EPAREN);
352 p->pbegin[subno] = HERE();
353 EMIT(OLPAREN, subno);
356 if (subno < NPAREN) {
357 p->pend[subno] = HERE();
358 assert(p->pend[subno] != 0);
360 EMIT(ORPAREN, subno);
361 MUSTEAT(')', REG_EPAREN);
363 #ifndef POSIX_MISTAKE
364 case ')': /* happens only if no current unmatched ( */
366 * You may ask, why the ifndef? Because I didn't notice
367 * this until slightly too late for 1003.2, and none of the
368 * other 1003.2 regular-expression reviewers noticed it at
369 * all. So an unmatched ) is legal POSIX, at least until
370 * we can get it fixed.
372 SETERROR(REG_EPAREN);
377 p->g->iflags |= USEBOL;
383 p->g->iflags |= USEEOL;
392 SETERROR(REG_BADRPT);
395 if (p->g->cflags®_NEWLINE)
404 REQUIRE(MORE(), REG_EESCAPE);
408 case '{': /* okay as ordinary except if digit follows */
409 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
421 /* we call { a repetition if followed by a digit */
422 if (!( c == '*' || c == '+' || c == '?' ||
423 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
424 return; /* no repetition, we're done */
427 REQUIRE(!wascaret, REG_BADRPT);
429 case '*': /* implemented as +? */
430 /* this case does not require the (y|) trick, noKLUDGE */
433 INSERT(OQUEST_, pos);
434 ASTERN(O_QUEST, pos);
441 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
442 INSERT(OCH_, pos); /* offset slightly wrong */
443 ASTERN(OOR1, pos); /* this one's right */
444 AHEAD(pos); /* fix the OCH_ */
445 EMIT(OOR2, 0); /* offset very wrong... */
446 AHEAD(THERE()); /* ...so fix it */
447 ASTERN(O_CH, THERETHERE());
452 if (isdigit((uch)PEEK())) {
454 REQUIRE(count <= count2, REG_BADBR);
455 } else /* single number with comma */
457 } else /* just a single number */
459 repeat(p, pos, count, count2);
460 if (!EAT('}')) { /* error heuristics */
461 while (MORE() && PEEK() != '}')
463 REQUIRE(MORE(), REG_EBRACE);
472 if (!( c == '*' || c == '+' || c == '?' ||
473 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
475 SETERROR(REG_BADRPT);
479 - p_str - string (no metacharacters) "parser"
480 == static void p_str(struct parse *p);
483 p_str(struct parse *p)
485 REQUIRE(MORE(), REG_EMPTY);
487 ordinary(p, WGETNEXT());
491 - p_bre - BRE parser top level, anchoring and concatenation
492 == static void p_bre(struct parse *p, int end1, \
494 * Giving end1 as OUT essentially eliminates the end1/end2 check.
496 * This implementation is a bit of a kludge, in that a trailing $ is first
497 * taken as an ordinary character and then revised to be an anchor.
498 * The amount of lookahead needed to avoid this kludge is excessive.
501 p_bre(struct parse *p,
502 int end1, /* first terminating character */
503 int end2) /* second terminating character */
505 sopno start = HERE();
506 int first = 1; /* first subexpression? */
511 p->g->iflags |= USEBOL;
514 while (MORE() && !SEETWO(end1, end2)) {
515 wasdollar = p_simp_re(p, first);
518 if (wasdollar) { /* oops, that was a trailing anchor */
521 p->g->iflags |= USEEOL;
525 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
529 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
530 == static int p_simp_re(struct parse *p, int starordinary);
532 static int /* was the simple RE an unbackslashed $? */
533 p_simp_re(struct parse *p,
534 int starordinary) /* is a leading * an ordinary character? */
543 # define BACKSL (1<<CHAR_BIT)
545 pos = HERE(); /* repetion op, if any, covers from here */
547 assert(MORE()); /* caller should have ensured this */
550 REQUIRE(MORE(), REG_EESCAPE);
551 c = BACKSL | GETNEXT();
555 if (p->g->cflags®_NEWLINE)
564 SETERROR(REG_BADRPT);
570 p->pbegin[subno] = HERE();
571 EMIT(OLPAREN, subno);
572 /* the MORE here is an error heuristic */
573 if (MORE() && !SEETWO('\\', ')'))
575 if (subno < NPAREN) {
576 p->pend[subno] = HERE();
577 assert(p->pend[subno] != 0);
579 EMIT(ORPAREN, subno);
580 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
582 case BACKSL|')': /* should not get here -- must be user */
584 SETERROR(REG_EPAREN);
595 i = (c&~BACKSL) - '0';
597 if (p->pend[i] != 0) {
598 assert(i <= p->g->nsub);
600 assert(p->pbegin[i] != 0);
601 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
602 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
603 dupl(p, p->pbegin[i]+1, p->pend[i]);
606 SETERROR(REG_ESUBREG);
610 REQUIRE(starordinary, REG_BADRPT);
619 if (EAT('*')) { /* implemented as +? */
620 /* this case does not require the (y|) trick, noKLUDGE */
623 INSERT(OQUEST_, pos);
624 ASTERN(O_QUEST, pos);
625 } else if (EATTWO('\\', '{')) {
628 if (MORE() && isdigit((uch)PEEK())) {
630 REQUIRE(count <= count2, REG_BADBR);
631 } else /* single number with comma */
633 } else /* just a single number */
635 repeat(p, pos, count, count2);
636 if (!EATTWO('\\', '}')) { /* error heuristics */
637 while (MORE() && !SEETWO('\\', '}'))
639 REQUIRE(MORE(), REG_EBRACE);
642 } else if (c == '$') /* $ (but not \$) ends it */
649 - p_count - parse a repetition count
650 == static int p_count(struct parse *p);
652 static int /* the value */
653 p_count(struct parse *p)
658 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
659 count = count*10 + (GETNEXT() - '0');
663 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
668 - p_bracket - parse a bracketed character list
669 == static void p_bracket(struct parse *p);
672 p_bracket(struct parse *p)
677 /* Dept of Truly Sickening Special-Case Kludges */
678 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
683 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
689 if ((cs = allocset(p)) == NULL)
692 if (p->g->cflags®_ICASE)
700 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
704 MUSTEAT(']', REG_EBRACK);
706 if (p->error != 0) /* don't mess things up further */
709 if (cs->invert && p->g->cflags®_NEWLINE)
710 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
712 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
716 EMIT(OANYOF, (int)(cs - p->g->sets));
720 - p_b_term - parse one term of a bracketed character list
721 == static void p_b_term(struct parse *p, cset *cs);
724 p_b_term(struct parse *p, cset *cs)
727 wint_t start, finish;
730 /* classify what we've got */
731 switch ((MORE()) ? PEEK() : '\0') {
733 c = (MORE2()) ? PEEK2() : '\0';
736 SETERROR(REG_ERANGE);
737 return; /* NOTE RETURN */
745 case ':': /* character class */
747 REQUIRE(MORE(), REG_EBRACK);
749 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
751 REQUIRE(MORE(), REG_EBRACK);
752 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
754 case '=': /* equivalence class */
756 REQUIRE(MORE(), REG_EBRACK);
758 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
760 REQUIRE(MORE(), REG_EBRACK);
761 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
763 default: /* symbol, ordinary character, or range */
764 start = p_b_symbol(p);
765 if (SEE('-') && MORE2() && PEEK2() != ']') {
771 finish = p_b_symbol(p);
777 if (__collate_load_error) {
778 REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
779 CHaddrange(p, cs, start, finish);
781 REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE);
782 for (i = 0; i <= UCHAR_MAX; i++) {
783 if ( __collate_range_cmp(start, i) <= 0
784 && __collate_range_cmp(i, finish) <= 0
795 - p_b_cclass - parse a character-class name and deal with it
796 == static void p_b_cclass(struct parse *p, cset *cs);
799 p_b_cclass(struct parse *p, cset *cs)
806 while (MORE() && isalpha((uch)PEEK()))
809 if (len >= sizeof(clname) - 1) {
810 SETERROR(REG_ECTYPE);
813 memcpy(clname, sp, len);
815 if ((wct = wctype(clname)) == 0) {
816 SETERROR(REG_ECTYPE);
819 CHaddtype(p, cs, wct);
823 - p_b_eclass - parse an equivalence-class name and deal with it
824 == static void p_b_eclass(struct parse *p, cset *cs);
826 * This implementation is incomplete. xxx
829 p_b_eclass(struct parse *p, cset *cs)
833 c = p_b_coll_elem(p, '=');
838 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
839 == static char p_b_symbol(struct parse *p);
841 static wint_t /* value of symbol */
842 p_b_symbol(struct parse *p)
846 REQUIRE(MORE(), REG_EBRACK);
847 if (!EATTWO('[', '.'))
850 /* collating symbol */
851 value = p_b_coll_elem(p, '.');
852 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
857 - p_b_coll_elem - parse a collating-element name and look it up
858 == static char p_b_coll_elem(struct parse *p, int endc);
860 static wint_t /* value of collating element */
861 p_b_coll_elem(struct parse *p,
862 wint_t endc) /* name ended by endc,']' */
871 while (MORE() && !SEETWO(endc, ']'))
874 SETERROR(REG_EBRACK);
878 for (cp = cnames; cp->name != NULL; cp++)
879 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
880 return(cp->code); /* known name */
881 memset(&mbs, 0, sizeof(mbs));
882 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
883 return (wc); /* single character */
884 else if (clen == (size_t)-1 || clen == (size_t)-2)
885 SETERROR(REG_ILLSEQ);
887 SETERROR(REG_ECOLLATE); /* neither */
892 - othercase - return the case counterpart of an alphabetic
893 == static char othercase(int ch);
895 static wint_t /* if no counterpart, return ch */
898 assert(iswalpha(ch));
900 return(towlower(ch));
901 else if (iswlower(ch))
902 return(towupper(ch));
903 else /* peculiar, but could happen */
908 - bothcases - emit a dualcase version of a two-case character
909 == static void bothcases(struct parse *p, int ch);
911 * Boy, is this implementation ever a kludge...
914 bothcases(struct parse *p, wint_t ch)
916 char *oldnext = p->next;
917 char *oldend = p->end;
918 char bracket[3 + MB_LEN_MAX];
922 assert(othercase(ch) != ch); /* p_bracket() would recurse */
924 memset(&mbs, 0, sizeof(mbs));
925 n = wcrtomb(bracket, ch, &mbs);
926 assert(n != (size_t)-1);
928 bracket[n + 1] = '\0';
929 p->end = bracket+n+1;
931 assert(p->next == p->end);
937 - ordinary - emit an ordinary character
938 == static void ordinary(struct parse *p, int ch);
941 ordinary(struct parse *p, wint_t ch)
945 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
947 else if ((ch & OPDMASK) == ch)
951 * Kludge: character is too big to fit into an OCHAR operand.
952 * Emit a singleton set.
954 if ((cs = allocset(p)) == NULL)
957 EMIT(OANYOF, (int)(cs - p->g->sets));
962 - nonnewline - emit REG_NEWLINE version of OANY
963 == static void nonnewline(struct parse *p);
965 * Boy, is this implementation ever a kludge...
968 nonnewline(struct parse *p)
970 char *oldnext = p->next;
971 char *oldend = p->end;
981 assert(p->next == bracket+3);
987 - repeat - generate code for a bounded repetition, recursively if needed
988 == static void repeat(struct parse *p, sopno start, int from, int to);
991 repeat(struct parse *p,
992 sopno start, /* operand from here to end of strip */
993 int from, /* repeated from this number */
994 int to) /* to this number of times (maybe INFINITY) */
996 sopno finish = HERE();
999 # define REP(f, t) ((f)*8 + (t))
1000 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1003 if (p->error != 0) /* head off possible runaway recursion */
1008 switch (REP(MAP(from), MAP(to))) {
1009 case REP(0, 0): /* must be user doing this */
1010 DROP(finish-start); /* drop the operand */
1012 case REP(0, 1): /* as x{1,1}? */
1013 case REP(0, N): /* as x{1,n}? */
1014 case REP(0, INF): /* as x{1,}? */
1015 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1016 INSERT(OCH_, start); /* offset is wrong... */
1017 repeat(p, start+1, 1, to);
1018 ASTERN(OOR1, start);
1019 AHEAD(start); /* ... fix it */
1022 ASTERN(O_CH, THERETHERE());
1024 case REP(1, 1): /* trivial case */
1027 case REP(1, N): /* as x?x{1,n-1} */
1028 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1029 INSERT(OCH_, start);
1030 ASTERN(OOR1, start);
1032 EMIT(OOR2, 0); /* offset very wrong... */
1033 AHEAD(THERE()); /* ...so fix it */
1034 ASTERN(O_CH, THERETHERE());
1035 copy = dupl(p, start+1, finish+1);
1036 assert(copy == finish+4);
1037 repeat(p, copy, 1, to-1);
1039 case REP(1, INF): /* as x+ */
1040 INSERT(OPLUS_, start);
1041 ASTERN(O_PLUS, start);
1043 case REP(N, N): /* as xx{m-1,n-1} */
1044 copy = dupl(p, start, finish);
1045 repeat(p, copy, from-1, to-1);
1047 case REP(N, INF): /* as xx{n-1,INF} */
1048 copy = dupl(p, start, finish);
1049 repeat(p, copy, from-1, to);
1051 default: /* "can't happen" */
1052 SETERROR(REG_ASSERT); /* just in case */
1058 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1059 - character from the parse struct, signals a REG_ILLSEQ error if the
1060 - character can't be converted. Returns the number of bytes consumed.
1063 wgetnext(struct parse *p)
1069 memset(&mbs, 0, sizeof(mbs));
1070 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1071 if (n == (size_t)-1 || n == (size_t)-2) {
1072 SETERROR(REG_ILLSEQ);
1082 - seterr - set an error condition
1083 == static int seterr(struct parse *p, int e);
1085 static int /* useless but makes type checking happy */
1086 seterr(struct parse *p, int e)
1088 if (p->error == 0) /* keep earliest error condition */
1090 p->next = nuls; /* try to bring things to a halt */
1092 return(0); /* make the return value well-defined */
1096 - allocset - allocate a set of characters for []
1097 == static cset *allocset(struct parse *p);
1100 allocset(struct parse *p)
1104 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1106 SETERROR(REG_ESPACE);
1110 cs = &p->g->sets[p->g->ncsets++];
1111 memset(cs, 0, sizeof(*cs));
1117 - freeset - free a now-unused set
1118 == static void freeset(struct parse *p, cset *cs);
1121 freeset(struct parse *p, cset *cs)
1123 cset *top = &p->g->sets[p->g->ncsets];
1128 memset(cs, 0, sizeof(*cs));
1129 if (cs == top-1) /* recover only the easy case */
1134 - singleton - Determine whether a set contains only one character,
1135 - returning it if so, otherwise returning OUT.
1142 for (i = n = 0; i < NC; i++)
1149 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1151 return (cs->wides[0]);
1152 /* Don't bother handling the other cases. */
1157 - CHadd - add character to character set.
1160 CHadd(struct parse *p, cset *cs, wint_t ch)
1162 wint_t nch, *newwides;
1165 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1167 newwides = realloc(cs->wides, (cs->nwides + 1) *
1168 sizeof(*cs->wides));
1169 if (newwides == NULL) {
1170 SETERROR(REG_ESPACE);
1173 cs->wides = newwides;
1174 cs->wides[cs->nwides++] = ch;
1177 if ((nch = towlower(ch)) < NC)
1178 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1179 if ((nch = towupper(ch)) < NC)
1180 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1185 - CHaddrange - add all characters in the range [min,max] to a character set.
1188 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1192 for (; min < NC && min <= max; min++)
1196 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1197 sizeof(*cs->ranges));
1198 if (newranges == NULL) {
1199 SETERROR(REG_ESPACE);
1202 cs->ranges = newranges;
1203 cs->ranges[cs->nranges].min = min;
1204 cs->ranges[cs->nranges].min = max;
1209 - CHaddtype - add all characters of a certain type to a character set.
1212 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1217 for (i = 0; i < NC; i++)
1218 if (iswctype(i, wct))
1220 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1221 sizeof(*cs->types));
1222 if (newtypes == NULL) {
1223 SETERROR(REG_ESPACE);
1226 cs->types = newtypes;
1227 cs->types[cs->ntypes++] = wct;
1231 - dupl - emit a duplicate of a bunch of sops
1232 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1234 static sopno /* start of duplicate */
1235 dupl(struct parse *p,
1236 sopno start, /* from here */
1237 sopno finish) /* to this less one */
1240 sopno len = finish - start;
1242 assert(finish >= start);
1245 enlarge(p, p->ssize + len); /* this many unexpected additions */
1246 assert(p->ssize >= p->slen + len);
1247 memcpy((char *)(p->strip + p->slen),
1248 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1254 - doemit - emit a strip operator
1255 == static void doemit(struct parse *p, sop op, size_t opnd);
1257 * It might seem better to implement this as a macro with a function as
1258 * hard-case backup, but it's just too big and messy unless there are
1259 * some changes to the data structures. Maybe later.
1262 doemit(struct parse *p, sop op, size_t opnd)
1264 /* avoid making error situations worse */
1268 /* deal with oversize operands ("can't happen", more or less) */
1269 assert(opnd < 1<<OPSHIFT);
1271 /* deal with undersized strip */
1272 if (p->slen >= p->ssize)
1273 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1274 assert(p->slen < p->ssize);
1276 /* finally, it's all reduced to the easy case */
1277 p->strip[p->slen++] = SOP(op, opnd);
1281 - doinsert - insert a sop into the strip
1282 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1285 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1291 /* avoid making error situations worse */
1296 EMIT(op, opnd); /* do checks, ensure space */
1297 assert(HERE() == sn+1);
1300 /* adjust paren pointers */
1302 for (i = 1; i < NPAREN; i++) {
1303 if (p->pbegin[i] >= pos) {
1306 if (p->pend[i] >= pos) {
1311 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1312 (HERE()-pos-1)*sizeof(sop));
1317 - dofwd - complete a forward reference
1318 == static void dofwd(struct parse *p, sopno pos, sop value);
1321 dofwd(struct parse *p, sopno pos, sop value)
1323 /* avoid making error situations worse */
1327 assert(value < 1<<OPSHIFT);
1328 p->strip[pos] = OP(p->strip[pos]) | value;
1332 - enlarge - enlarge the strip
1333 == static void enlarge(struct parse *p, sopno size);
1336 enlarge(struct parse *p, sopno size)
1340 if (p->ssize >= size)
1343 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1345 SETERROR(REG_ESPACE);
1353 - stripsnug - compact the strip
1354 == static void stripsnug(struct parse *p, struct re_guts *g);
1357 stripsnug(struct parse *p, struct re_guts *g)
1359 g->nstates = p->slen;
1360 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1361 if (g->strip == NULL) {
1362 SETERROR(REG_ESPACE);
1363 g->strip = p->strip;
1368 - findmust - fill in must and mlen with longest mandatory literal string
1369 == static void findmust(struct parse *p, struct re_guts *g);
1371 * This algorithm could do fancy things like analyzing the operands of |
1372 * for common subsequences. Someday. This code is simple and finds most
1373 * of the interesting cases.
1375 * Note that must and mlen got initialized during setup.
1378 findmust(struct parse *p, struct re_guts *g)
1387 char buf[MB_LEN_MAX];
1391 /* avoid making error situations worse */
1396 * It's not generally safe to do a ``char'' substring search on
1397 * multibyte character strings, but it's safe for at least
1398 * UTF-8 (see RFC 3629).
1400 if (MB_CUR_MAX > 1 &&
1401 strcmp(nl_langinfo(CODESET), "UTF-8") != 0)
1404 /* find the longest OCHAR sequence in strip */
1408 scan = g->strip + 1;
1412 case OCHAR: /* sequence member */
1413 if (newlen == 0) { /* new sequence */
1414 memset(&mbs, 0, sizeof(mbs));
1415 newstart = scan - 1;
1417 clen = wcrtomb(buf, OPND(s), &mbs);
1418 if (clen == (size_t)-1)
1422 case OPLUS_: /* things that don't break one */
1426 case OQUEST_: /* things that must be skipped */
1428 offset = altoffset(scan, offset);
1433 /* assert() interferes w debug printouts */
1434 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1439 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1441 case OBOW: /* things that break a sequence */
1448 if (newlen > g->mlen) { /* ends one */
1452 g->moffset += offset;
1455 g->moffset = offset;
1463 if (newlen > g->mlen) { /* ends one */
1467 g->moffset += offset;
1470 g->moffset = offset;
1479 case OANYOF: /* may or may not invalidate offset */
1480 /* First, everything as OANY */
1481 if (newlen > g->mlen) { /* ends one */
1485 g->moffset += offset;
1488 g->moffset = offset;
1499 /* Anything here makes it impossible or too hard
1500 * to calculate the offset -- so we give up;
1501 * save the last known good offset, in case the
1502 * must sequence doesn't occur later.
1504 if (newlen > g->mlen) { /* ends one */
1508 g->moffset += offset;
1510 g->moffset = offset;
1516 } while (OP(s) != OEND);
1518 if (g->mlen == 0) { /* there isn't one */
1523 /* turn it into a character string */
1524 g->must = malloc((size_t)g->mlen + 1);
1525 if (g->must == NULL) { /* argh; just forget it */
1532 memset(&mbs, 0, sizeof(mbs));
1533 while (cp < g->must + g->mlen) {
1534 while (OP(s = *scan++) != OCHAR)
1536 clen = wcrtomb(cp, OPND(s), &mbs);
1537 assert(clen != (size_t)-1);
1540 assert(cp == g->must + g->mlen);
1541 *cp++ = '\0'; /* just on general principles */
1545 - altoffset - choose biggest offset among multiple choices
1546 == static int altoffset(sop *scan, int offset);
1548 * Compute, recursively if necessary, the largest offset among multiple
1552 altoffset(sop *scan, int offset)
1558 /* If we gave up already on offsets, return */
1565 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1574 try = altoffset(scan, try);
1581 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1584 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1585 /* We must skip to the next position, or we'll
1586 * leave altoffset() too early.
1612 return largest+offset;
1616 - computejumps - compute char jumps for BM scan
1617 == static void computejumps(struct parse *p, struct re_guts *g);
1619 * This algorithm assumes g->must exists and is has size greater than
1620 * zero. It's based on the algorithm found on Computer Algorithms by
1623 * A char jump is the number of characters one needs to jump based on
1624 * the value of the character from the text that was mismatched.
1627 computejumps(struct parse *p, struct re_guts *g)
1632 /* Avoid making errors worse */
1636 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1637 if (g->charjump == NULL) /* Not a fatal error */
1639 /* Adjust for signed chars, if necessary */
1640 g->charjump = &g->charjump[-(CHAR_MIN)];
1642 /* If the character does not exist in the pattern, the jump
1643 * is equal to the number of characters in the pattern.
1645 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1646 g->charjump[ch] = g->mlen;
1648 /* If the character does exist, compute the jump that would
1649 * take us to the last character in the pattern equal to it
1650 * (notice that we match right to left, so that last character
1651 * is the first one that would be matched).
1653 for (mindex = 0; mindex < g->mlen; mindex++)
1654 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1658 - computematchjumps - compute match jumps for BM scan
1659 == static void computematchjumps(struct parse *p, struct re_guts *g);
1661 * This algorithm assumes g->must exists and is has size greater than
1662 * zero. It's based on the algorithm found on Computer Algorithms by
1665 * A match jump is the number of characters one needs to advance based
1666 * on the already-matched suffix.
1667 * Notice that all values here are minus (g->mlen-1), because of the way
1668 * the search algorithm works.
1671 computematchjumps(struct parse *p, struct re_guts *g)
1673 int mindex; /* General "must" iterator */
1674 int suffix; /* Keeps track of matching suffix */
1675 int ssuffix; /* Keeps track of suffixes' suffix */
1676 int* pmatches; /* pmatches[k] points to the next i
1677 * such that i+1...mlen is a substring
1678 * of k+1...k+mlen-i-1
1681 /* Avoid making errors worse */
1685 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1686 if (pmatches == NULL) {
1687 g->matchjump = NULL;
1691 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1692 if (g->matchjump == NULL) /* Not a fatal error */
1695 /* Set maximum possible jump for each character in the pattern */
1696 for (mindex = 0; mindex < g->mlen; mindex++)
1697 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1699 /* Compute pmatches[] */
1700 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1701 mindex--, suffix--) {
1702 pmatches[mindex] = suffix;
1704 /* If a mismatch is found, interrupting the substring,
1705 * compute the matchjump for that position. If no
1706 * mismatch is found, then a text substring mismatched
1707 * against the suffix will also mismatch against the
1710 while (suffix < g->mlen
1711 && g->must[mindex] != g->must[suffix]) {
1712 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1713 g->mlen - mindex - 1);
1714 suffix = pmatches[suffix];
1718 /* Compute the matchjump up to the last substring found to jump
1719 * to the beginning of the largest must pattern prefix matching
1722 for (mindex = 0; mindex <= suffix; mindex++)
1723 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1724 g->mlen + suffix - mindex);
1726 ssuffix = pmatches[suffix];
1727 while (suffix < g->mlen) {
1728 while (suffix <= ssuffix && suffix < g->mlen) {
1729 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1730 g->mlen + ssuffix - suffix);
1733 if (suffix < g->mlen)
1734 ssuffix = pmatches[ssuffix];
1741 - pluscount - count + nesting
1742 == static sopno pluscount(struct parse *p, struct re_guts *g);
1744 static sopno /* nesting depth */
1745 pluscount(struct parse *p, struct re_guts *g)
1753 return(0); /* there may not be an OEND */
1755 scan = g->strip + 1;
1763 if (plusnest > maxnest)
1768 } while (OP(s) != OEND);