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 * Copyright (c) 2011 The FreeBSD Foundation
8 * Portions of this software were developed by David Chisnall
9 * under sponsorship from the FreeBSD Foundation.
11 * This code is derived from software contributed to Berkeley by
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
39 * $FreeBSD: head/lib/libc/regex/regcomp.c 247596 2013-03-01 23:26:13Z delphij $
41 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
44 #include <sys/types.h>
63 * parse structure, passed up and down to avoid global variables and
67 char *next; /* next character in RE */
68 char *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 refs */
76 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
77 sopno pend[NPAREN]; /* -> ) ([0] unused) */
80 /* ========= begin header generated by ./mkh ========= */
85 /* === regcomp.c === */
86 static void p_ere(struct parse *p, int stop);
87 static void p_ere_exp(struct parse *p);
88 static void p_str(struct parse *p);
89 static void p_bre(struct parse *p, int end1, int end2);
90 static int p_simp_re(struct parse *p, int starordinary);
91 static int p_count(struct parse *p);
92 static void p_bracket(struct parse *p);
93 static void p_b_term(struct parse *p, cset *cs);
94 static void p_b_cclass(struct parse *p, cset *cs);
95 static void p_b_eclass(struct parse *p, cset *cs);
96 static wint_t p_b_symbol(struct parse *p);
97 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
98 static wint_t othercase(wint_t ch);
99 static void bothcases(struct parse *p, wint_t ch);
100 static void ordinary(struct parse *p, wint_t ch);
101 static void nonnewline(struct parse *p);
102 static void repeat(struct parse *p, sopno start, int from, int to);
103 static int seterr(struct parse *p, int e);
104 static cset *allocset(struct parse *p);
105 static void freeset(struct parse *p, cset *cs);
106 static void CHadd(struct parse *p, cset *cs, wint_t ch);
107 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
108 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
109 static wint_t singleton(cset *cs);
110 static sopno dupl(struct parse *p, sopno start, sopno finish);
111 static void doemit(struct parse *p, sop op, size_t opnd);
112 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
113 static void dofwd(struct parse *p, sopno pos, sop value);
114 static int enlarge(struct parse *p, sopno size);
115 static void stripsnug(struct parse *p, struct re_guts *g);
116 static void findmust(struct parse *p, struct re_guts *g);
117 static int altoffset(sop *scan, int offset);
118 static void computejumps(struct parse *p, struct re_guts *g);
119 static void computematchjumps(struct parse *p, struct re_guts *g);
120 static sopno pluscount(struct parse *p, struct re_guts *g);
121 static wint_t wgetnext(struct parse *p);
126 /* ========= end header generated by ./mkh ========= */
128 static char nuls[10]; /* place to point scanner in event of error */
131 * macros for use with parse structure
132 * BEWARE: these know that the parse structure is named `p' !!!
134 #define PEEK() (*p->next)
135 #define PEEK2() (*(p->next+1))
136 #define MORE() (p->next < p->end)
137 #define MORE2() (p->next+1 < p->end)
138 #define SEE(c) (MORE() && PEEK() == (c))
139 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
140 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
141 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
142 #define NEXT() (p->next++)
143 #define NEXT2() (p->next += 2)
144 #define NEXTn(n) (p->next += (n))
145 #define GETNEXT() (*p->next++)
146 #define WGETNEXT() wgetnext(p)
147 #define SETERROR(e) seterr(p, (e))
148 #define REQUIRE(co, e) ((co) || SETERROR(e))
149 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
150 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
151 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
152 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
153 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
154 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
155 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
156 #define HERE() (p->slen)
157 #define THERE() (p->slen - 1)
158 #define THERETHERE() (p->slen - 2)
159 #define DROP(n) (p->slen -= (n))
162 static int never = 0; /* for use in asserts; shuts lint up */
164 #define never 0 /* some <assert.h>s have bugs too */
167 /* Macro used by computejump()/computematchjump() */
168 #define MIN(a,b) ((a)<(b)?(a):(b))
171 - regcomp - interface for parser and compilation
172 = extern int regcomp(regex_t *, const char *, int);
173 = #define REG_BASIC 0000
174 = #define REG_EXTENDED 0001
175 = #define REG_ICASE 0002
176 = #define REG_NOSUB 0004
177 = #define REG_NEWLINE 0010
178 = #define REG_NOSPEC 0020
179 = #define REG_PEND 0040
180 = #define REG_DUMP 0200
182 int /* 0 success, otherwise REG_something */
183 regcomp(regex_t * __restrict preg,
184 const char * __restrict pattern,
189 struct parse *p = &pa;
194 # define GOODFLAGS(f) (f)
196 # define GOODFLAGS(f) ((f)&~REG_DUMP)
199 cflags = GOODFLAGS(cflags);
200 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
203 if (cflags®_PEND) {
204 if (preg->re_endp < pattern)
206 len = preg->re_endp - pattern;
208 len = strlen((char *)pattern);
210 /* do the mallocs early so failure handling is easy */
211 g = (struct re_guts *)malloc(sizeof(struct re_guts));
215 * Limit the pattern space to avoid a 32-bit overflow on buffer
216 * extension. Also avoid any signed overflow in case of conversion
217 * so make the real limit based on a 31-bit overflow.
219 * Likely not applicable on 64-bit systems but handle the case
220 * generically (who are we to stop people from using ~715MB+
223 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
228 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
229 assert(p->ssize >= len);
231 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
233 if (p->strip == NULL) {
240 p->next = (char *)pattern; /* convenience; we do not modify it */
241 p->end = p->next + len;
244 for (i = 0; i < NPAREN; i++) {
264 g->firststate = THERE();
265 if (cflags®_EXTENDED)
267 else if (cflags®_NOSPEC)
272 g->laststate = THERE();
274 /* tidy up loose ends and fill things in */
277 /* only use Boyer-Moore algorithm if the pattern is bigger
278 * than three characters
282 computematchjumps(p, g);
283 if(g->matchjump == NULL && g->charjump != NULL) {
288 g->nplus = pluscount(p, g);
290 preg->re_nsub = g->nsub;
292 preg->re_magic = MAGIC1;
294 /* not debugging, so can't rely on the assert() in regexec() */
296 SETERROR(REG_ASSERT);
299 /* win or lose, we're done */
300 if (p->error != 0) /* lose */
306 - p_ere - ERE parser top level, concatenation and alternation
307 == static void p_ere(struct parse *p, int_t stop);
310 p_ere(struct parse *p,
311 int stop) /* character this ERE should end at */
317 int first = 1; /* is this the first alternative? */
320 /* do a bunch of concatenated expressions */
322 while (MORE() && (c = PEEK()) != '|' && c != stop)
324 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
327 break; /* NOTE BREAK OUT */
330 INSERT(OCH_, conc); /* offset is wrong */
335 ASTERN(OOR1, prevback);
337 AHEAD(prevfwd); /* fix previous offset */
339 EMIT(OOR2, 0); /* offset is very wrong */
342 if (!first) { /* tail-end fixups */
344 ASTERN(O_CH, prevback);
347 assert(!MORE() || SEE(stop));
351 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
352 == static void p_ere_exp(struct parse *p);
355 p_ere_exp(struct parse *p)
365 assert(MORE()); /* caller should have ensured this */
371 (void)REQUIRE(MORE(), REG_EPAREN);
375 p->pbegin[subno] = HERE();
376 EMIT(OLPAREN, subno);
379 if (subno < NPAREN) {
380 p->pend[subno] = HERE();
381 assert(p->pend[subno] != 0);
383 EMIT(ORPAREN, subno);
384 (void)MUSTEAT(')', REG_EPAREN);
386 #ifndef POSIX_MISTAKE
387 case ')': /* happens only if no current unmatched ( */
389 * You may ask, why the ifndef? Because I didn't notice
390 * this until slightly too late for 1003.2, and none of the
391 * other 1003.2 regular-expression reviewers noticed it at
392 * all. So an unmatched ) is legal POSIX, at least until
393 * we can get it fixed.
395 SETERROR(REG_EPAREN);
400 p->g->iflags |= USEBOL;
406 p->g->iflags |= USEEOL;
415 SETERROR(REG_BADRPT);
418 if (p->g->cflags®_NEWLINE)
427 (void)REQUIRE(MORE(), REG_EESCAPE);
431 case '{': /* okay as ordinary except if digit follows */
432 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
444 /* we call { a repetition if followed by a digit */
445 if (!( c == '*' || c == '+' || c == '?' ||
446 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
447 return; /* no repetition, we're done */
450 (void)REQUIRE(!wascaret, REG_BADRPT);
452 case '*': /* implemented as +? */
453 /* this case does not require the (y|) trick, noKLUDGE */
456 INSERT(OQUEST_, pos);
457 ASTERN(O_QUEST, pos);
464 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
465 INSERT(OCH_, pos); /* offset slightly wrong */
466 ASTERN(OOR1, pos); /* this one's right */
467 AHEAD(pos); /* fix the OCH_ */
468 EMIT(OOR2, 0); /* offset very wrong... */
469 AHEAD(THERE()); /* ...so fix it */
470 ASTERN(O_CH, THERETHERE());
475 if (isdigit((uch)PEEK())) {
477 (void)REQUIRE(count <= count2, REG_BADBR);
478 } else /* single number with comma */
480 } else /* just a single number */
482 repeat(p, pos, count, count2);
483 if (!EAT('}')) { /* error heuristics */
484 while (MORE() && PEEK() != '}')
486 (void)REQUIRE(MORE(), REG_EBRACE);
495 if (!( c == '*' || c == '+' || c == '?' ||
496 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
498 SETERROR(REG_BADRPT);
502 - p_str - string (no metacharacters) "parser"
503 == static void p_str(struct parse *p);
506 p_str(struct parse *p)
508 (void)REQUIRE(MORE(), REG_EMPTY);
510 ordinary(p, WGETNEXT());
514 - p_bre - BRE parser top level, anchoring and concatenation
515 == static void p_bre(struct parse *p, int end1, \
517 * Giving end1 as OUT essentially eliminates the end1/end2 check.
519 * This implementation is a bit of a kludge, in that a trailing $ is first
520 * taken as an ordinary character and then revised to be an anchor.
521 * The amount of lookahead needed to avoid this kludge is excessive.
524 p_bre(struct parse *p,
525 int end1, /* first terminating character */
526 int end2) /* second terminating character */
528 sopno start = HERE();
529 int first = 1; /* first subexpression? */
534 p->g->iflags |= USEBOL;
537 while (MORE() && !SEETWO(end1, end2)) {
538 wasdollar = p_simp_re(p, first);
541 if (wasdollar) { /* oops, that was a trailing anchor */
544 p->g->iflags |= USEEOL;
548 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
552 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
553 == static int p_simp_re(struct parse *p, int starordinary);
555 static int /* was the simple RE an unbackslashed $? */
556 p_simp_re(struct parse *p,
557 int starordinary) /* is a leading * an ordinary character? */
566 # define BACKSL (1<<CHAR_BIT)
568 pos = HERE(); /* repetion op, if any, covers from here */
570 assert(MORE()); /* caller should have ensured this */
573 (void)REQUIRE(MORE(), REG_EESCAPE);
574 c = BACKSL | GETNEXT();
578 if (p->g->cflags®_NEWLINE)
587 SETERROR(REG_BADRPT);
593 p->pbegin[subno] = HERE();
594 EMIT(OLPAREN, subno);
595 /* the MORE here is an error heuristic */
596 if (MORE() && !SEETWO('\\', ')'))
598 if (subno < NPAREN) {
599 p->pend[subno] = HERE();
600 assert(p->pend[subno] != 0);
602 EMIT(ORPAREN, subno);
603 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
605 case BACKSL|')': /* should not get here -- must be user */
607 SETERROR(REG_EPAREN);
618 i = (c&~BACKSL) - '0';
620 if (p->pend[i] != 0) {
621 assert(i <= p->g->nsub);
623 assert(p->pbegin[i] != 0);
624 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
625 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
626 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
629 SETERROR(REG_ESUBREG);
633 (void)REQUIRE(starordinary, REG_BADRPT);
642 if (EAT('*')) { /* implemented as +? */
643 /* this case does not require the (y|) trick, noKLUDGE */
646 INSERT(OQUEST_, pos);
647 ASTERN(O_QUEST, pos);
648 } else if (EATTWO('\\', '{')) {
651 if (MORE() && isdigit((uch)PEEK())) {
653 (void)REQUIRE(count <= count2, REG_BADBR);
654 } else /* single number with comma */
656 } else /* just a single number */
658 repeat(p, pos, count, count2);
659 if (!EATTWO('\\', '}')) { /* error heuristics */
660 while (MORE() && !SEETWO('\\', '}'))
662 (void)REQUIRE(MORE(), REG_EBRACE);
665 } else if (c == '$') /* $ (but not \$) ends it */
672 - p_count - parse a repetition count
673 == static int p_count(struct parse *p);
675 static int /* the value */
676 p_count(struct parse *p)
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(struct parse *p);
695 p_bracket(struct parse *p)
700 /* Dept of Truly Sickening Special-Case Kludges */
701 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
706 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
712 if ((cs = allocset(p)) == NULL)
715 if (p->g->cflags®_ICASE)
723 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
727 (void)MUSTEAT(']', REG_EBRACK);
729 if (p->error != 0) /* don't mess things up further */
732 if (cs->invert && p->g->cflags®_NEWLINE)
733 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
735 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
739 EMIT(OANYOF, (int)(cs - p->g->sets));
743 - p_b_term - parse one term of a bracketed character list
744 == static void p_b_term(struct parse *p, cset *cs);
747 p_b_term(struct parse *p, cset *cs)
750 wint_t start, finish;
752 struct xlocale_collate *table =
753 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
755 /* classify what we've got */
756 switch ((MORE()) ? PEEK() : '\0') {
758 c = (MORE2()) ? PEEK2() : '\0';
761 SETERROR(REG_ERANGE);
762 return; /* NOTE RETURN */
770 case ':': /* character class */
772 (void)REQUIRE(MORE(), REG_EBRACK);
774 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
776 (void)REQUIRE(MORE(), REG_EBRACK);
777 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
779 case '=': /* equivalence class */
781 (void)REQUIRE(MORE(), REG_EBRACK);
783 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
785 (void)REQUIRE(MORE(), REG_EBRACK);
786 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
788 default: /* symbol, ordinary character, or range */
789 start = p_b_symbol(p);
790 if (SEE('-') && MORE2() && PEEK2() != ']') {
796 finish = p_b_symbol(p);
802 if (table->__collate_load_error) {
803 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
804 CHaddrange(p, cs, start, finish);
806 (void)REQUIRE(__collate_range_cmp(table, start, finish) <= 0, REG_ERANGE);
807 for (i = 0; i <= UCHAR_MAX; i++) {
808 if ( __collate_range_cmp(table, start, i) <= 0
809 && __collate_range_cmp(table, i, finish) <= 0
820 - p_b_cclass - parse a character-class name and deal with it
821 == static void p_b_cclass(struct parse *p, cset *cs);
824 p_b_cclass(struct parse *p, cset *cs)
831 while (MORE() && isalpha((uch)PEEK()))
834 if (len >= sizeof(clname) - 1) {
835 SETERROR(REG_ECTYPE);
838 memcpy(clname, sp, len);
840 if ((wct = wctype(clname)) == 0) {
841 SETERROR(REG_ECTYPE);
844 CHaddtype(p, cs, wct);
848 - p_b_eclass - parse an equivalence-class name and deal with it
849 == static void p_b_eclass(struct parse *p, cset *cs);
851 * This implementation is incomplete. xxx
854 p_b_eclass(struct parse *p, cset *cs)
858 c = p_b_coll_elem(p, '=');
863 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
864 == static wint_t p_b_symbol(struct parse *p);
866 static wint_t /* value of symbol */
867 p_b_symbol(struct parse *p)
871 (void)REQUIRE(MORE(), REG_EBRACK);
872 if (!EATTWO('[', '.'))
875 /* collating symbol */
876 value = p_b_coll_elem(p, '.');
877 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
882 - p_b_coll_elem - parse a collating-element name and look it up
883 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
885 static wint_t /* value of collating element */
886 p_b_coll_elem(struct parse *p,
887 wint_t endc) /* name ended by endc,']' */
896 while (MORE() && !SEETWO(endc, ']'))
899 SETERROR(REG_EBRACK);
903 for (cp = cnames; cp->name != NULL; cp++)
904 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
905 return(cp->code); /* known name */
906 memset(&mbs, 0, sizeof(mbs));
907 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
908 return (wc); /* single character */
909 else if (clen == (size_t)-1 || clen == (size_t)-2)
910 SETERROR(REG_ILLSEQ);
912 SETERROR(REG_ECOLLATE); /* neither */
917 - othercase - return the case counterpart of an alphabetic
918 == static wint_t othercase(wint_t ch);
920 static wint_t /* if no counterpart, return ch */
923 assert(iswalpha(ch));
925 return(towlower(ch));
926 else if (iswlower(ch))
927 return(towupper(ch));
928 else /* peculiar, but could happen */
933 - bothcases - emit a dualcase version of a two-case character
934 == static void bothcases(struct parse *p, wint_t ch);
936 * Boy, is this implementation ever a kludge...
939 bothcases(struct parse *p, wint_t ch)
941 char *oldnext = p->next;
942 char *oldend = p->end;
943 char bracket[3 + MB_LEN_MAX];
947 assert(othercase(ch) != ch); /* p_bracket() would recurse */
949 memset(&mbs, 0, sizeof(mbs));
950 n = wcrtomb(bracket, ch, &mbs);
951 assert(n != (size_t)-1);
953 bracket[n + 1] = '\0';
954 p->end = bracket+n+1;
956 assert(p->next == p->end);
962 - ordinary - emit an ordinary character
963 == static void ordinary(struct parse *p, wint_t ch);
966 ordinary(struct parse *p, wint_t ch)
970 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
972 else if ((ch & OPDMASK) == ch)
976 * Kludge: character is too big to fit into an OCHAR operand.
977 * Emit a singleton set.
979 if ((cs = allocset(p)) == NULL)
982 EMIT(OANYOF, (int)(cs - p->g->sets));
987 - nonnewline - emit REG_NEWLINE version of OANY
988 == static void nonnewline(struct parse *p);
990 * Boy, is this implementation ever a kludge...
993 nonnewline(struct parse *p)
995 char *oldnext = p->next;
996 char *oldend = p->end;
1006 assert(p->next == bracket+3);
1012 - repeat - generate code for a bounded repetition, recursively if needed
1013 == static void repeat(struct parse *p, sopno start, int from, int to);
1016 repeat(struct parse *p,
1017 sopno start, /* operand from here to end of strip */
1018 int from, /* repeated from this number */
1019 int to) /* to this number of times (maybe INFINITY) */
1021 sopno finish = HERE();
1024 # define REP(f, t) ((f)*8 + (t))
1025 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1028 if (p->error != 0) /* head off possible runaway recursion */
1033 switch (REP(MAP(from), MAP(to))) {
1034 case REP(0, 0): /* must be user doing this */
1035 DROP(finish-start); /* drop the operand */
1037 case REP(0, 1): /* as x{1,1}? */
1038 case REP(0, N): /* as x{1,n}? */
1039 case REP(0, INF): /* as x{1,}? */
1040 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1041 INSERT(OCH_, start); /* offset is wrong... */
1042 repeat(p, start+1, 1, to);
1043 ASTERN(OOR1, start);
1044 AHEAD(start); /* ... fix it */
1047 ASTERN(O_CH, THERETHERE());
1049 case REP(1, 1): /* trivial case */
1052 case REP(1, N): /* as x?x{1,n-1} */
1053 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1054 INSERT(OCH_, start);
1055 ASTERN(OOR1, start);
1057 EMIT(OOR2, 0); /* offset very wrong... */
1058 AHEAD(THERE()); /* ...so fix it */
1059 ASTERN(O_CH, THERETHERE());
1060 copy = dupl(p, start+1, finish+1);
1061 assert(copy == finish+4);
1062 repeat(p, copy, 1, to-1);
1064 case REP(1, INF): /* as x+ */
1065 INSERT(OPLUS_, start);
1066 ASTERN(O_PLUS, start);
1068 case REP(N, N): /* as xx{m-1,n-1} */
1069 copy = dupl(p, start, finish);
1070 repeat(p, copy, from-1, to-1);
1072 case REP(N, INF): /* as xx{n-1,INF} */
1073 copy = dupl(p, start, finish);
1074 repeat(p, copy, from-1, to);
1076 default: /* "can't happen" */
1077 SETERROR(REG_ASSERT); /* just in case */
1083 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1084 - character from the parse struct, signals a REG_ILLSEQ error if the
1085 - character can't be converted. Returns the number of bytes consumed.
1088 wgetnext(struct parse *p)
1094 memset(&mbs, 0, sizeof(mbs));
1095 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1096 if (n == (size_t)-1 || n == (size_t)-2) {
1097 SETERROR(REG_ILLSEQ);
1107 - seterr - set an error condition
1108 == static int seterr(struct parse *p, int e);
1110 static int /* useless but makes type checking happy */
1111 seterr(struct parse *p, int e)
1113 if (p->error == 0) /* keep earliest error condition */
1115 p->next = nuls; /* try to bring things to a halt */
1117 return(0); /* make the return value well-defined */
1121 - allocset - allocate a set of characters for []
1122 == static cset *allocset(struct parse *p);
1125 allocset(struct parse *p)
1129 ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs));
1131 SETERROR(REG_ESPACE);
1135 cs = &p->g->sets[p->g->ncsets++];
1136 memset(cs, 0, sizeof(*cs));
1142 - freeset - free a now-unused set
1143 == static void freeset(struct parse *p, cset *cs);
1146 freeset(struct parse *p, cset *cs)
1148 cset *top = &p->g->sets[p->g->ncsets];
1153 memset(cs, 0, sizeof(*cs));
1154 if (cs == top-1) /* recover only the easy case */
1159 - singleton - Determine whether a set contains only one character,
1160 - returning it if so, otherwise returning OUT.
1167 for (i = n = 0; i < NC; i++)
1174 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1176 return (cs->wides[0]);
1177 /* Don't bother handling the other cases. */
1182 - CHadd - add character to character set.
1185 CHadd(struct parse *p, cset *cs, wint_t ch)
1187 wint_t nch, *newwides;
1190 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1192 newwides = realloc(cs->wides, (cs->nwides + 1) *
1193 sizeof(*cs->wides));
1194 if (newwides == NULL) {
1195 SETERROR(REG_ESPACE);
1198 cs->wides = newwides;
1199 cs->wides[cs->nwides++] = ch;
1202 if ((nch = towlower(ch)) < NC)
1203 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1204 if ((nch = towupper(ch)) < NC)
1205 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1210 - CHaddrange - add all characters in the range [min,max] to a character set.
1213 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1217 for (; min < NC && min <= max; min++)
1221 newranges = realloc(cs->ranges, (cs->nranges + 1) *
1222 sizeof(*cs->ranges));
1223 if (newranges == NULL) {
1224 SETERROR(REG_ESPACE);
1227 cs->ranges = newranges;
1228 cs->ranges[cs->nranges].min = min;
1229 cs->ranges[cs->nranges].max = max;
1234 - CHaddtype - add all characters of a certain type to a character set.
1237 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1242 for (i = 0; i < NC; i++)
1243 if (iswctype(i, wct))
1245 newtypes = realloc(cs->types, (cs->ntypes + 1) *
1246 sizeof(*cs->types));
1247 if (newtypes == NULL) {
1248 SETERROR(REG_ESPACE);
1251 cs->types = newtypes;
1252 cs->types[cs->ntypes++] = wct;
1256 - dupl - emit a duplicate of a bunch of sops
1257 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1259 static sopno /* start of duplicate */
1260 dupl(struct parse *p,
1261 sopno start, /* from here */
1262 sopno finish) /* to this less one */
1265 sopno len = finish - start;
1267 assert(finish >= start);
1270 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1272 (void) memcpy((char *)(p->strip + p->slen),
1273 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1279 - doemit - emit a strip operator
1280 == static void doemit(struct parse *p, sop op, size_t opnd);
1282 * It might seem better to implement this as a macro with a function as
1283 * hard-case backup, but it's just too big and messy unless there are
1284 * some changes to the data structures. Maybe later.
1287 doemit(struct parse *p, sop op, size_t opnd)
1289 /* avoid making error situations worse */
1293 /* deal with oversize operands ("can't happen", more or less) */
1294 assert(opnd < 1<<OPSHIFT);
1296 /* deal with undersized strip */
1297 if (p->slen >= p->ssize)
1298 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1301 /* finally, it's all reduced to the easy case */
1302 p->strip[p->slen++] = SOP(op, opnd);
1306 - doinsert - insert a sop into the strip
1307 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1310 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1316 /* avoid making error situations worse */
1321 EMIT(op, opnd); /* do checks, ensure space */
1322 assert(HERE() == sn+1);
1325 /* adjust paren pointers */
1327 for (i = 1; i < NPAREN; i++) {
1328 if (p->pbegin[i] >= pos) {
1331 if (p->pend[i] >= pos) {
1336 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1337 (HERE()-pos-1)*sizeof(sop));
1342 - dofwd - complete a forward reference
1343 == static void dofwd(struct parse *p, sopno pos, sop value);
1346 dofwd(struct parse *p, sopno pos, sop value)
1348 /* avoid making error situations worse */
1352 assert(value < 1<<OPSHIFT);
1353 p->strip[pos] = OP(p->strip[pos]) | value;
1357 - enlarge - enlarge the strip
1358 == static int enlarge(struct parse *p, sopno size);
1361 enlarge(struct parse *p, sopno size)
1365 if (p->ssize >= size)
1368 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1370 SETERROR(REG_ESPACE);
1379 - stripsnug - compact the strip
1380 == static void stripsnug(struct parse *p, struct re_guts *g);
1383 stripsnug(struct parse *p, struct re_guts *g)
1385 g->nstates = p->slen;
1386 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1387 if (g->strip == NULL) {
1388 SETERROR(REG_ESPACE);
1389 g->strip = p->strip;
1394 - findmust - fill in must and mlen with longest mandatory literal string
1395 == static void findmust(struct parse *p, struct re_guts *g);
1397 * This algorithm could do fancy things like analyzing the operands of |
1398 * for common subsequences. Someday. This code is simple and finds most
1399 * of the interesting cases.
1401 * Note that must and mlen got initialized during setup.
1404 findmust(struct parse *p, struct re_guts *g)
1413 char buf[MB_LEN_MAX];
1417 /* avoid making error situations worse */
1422 * It's not generally safe to do a ``char'' substring search on
1423 * multibyte character strings, but it's safe for at least
1424 * UTF-8 (see RFC 3629).
1426 if (MB_CUR_MAX > 1 &&
1427 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1430 /* find the longest OCHAR sequence in strip */
1434 scan = g->strip + 1;
1438 case OCHAR: /* sequence member */
1439 if (newlen == 0) { /* new sequence */
1440 memset(&mbs, 0, sizeof(mbs));
1441 newstart = scan - 1;
1443 clen = wcrtomb(buf, OPND(s), &mbs);
1444 if (clen == (size_t)-1)
1448 case OPLUS_: /* things that don't break one */
1452 case OQUEST_: /* things that must be skipped */
1454 offset = altoffset(scan, offset);
1459 /* assert() interferes w debug printouts */
1460 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1465 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1467 case OBOW: /* things that break a sequence */
1474 if (newlen > g->mlen) { /* ends one */
1478 g->moffset += offset;
1481 g->moffset = offset;
1489 if (newlen > g->mlen) { /* ends one */
1493 g->moffset += offset;
1496 g->moffset = offset;
1505 case OANYOF: /* may or may not invalidate offset */
1506 /* First, everything as OANY */
1507 if (newlen > g->mlen) { /* ends one */
1511 g->moffset += offset;
1514 g->moffset = offset;
1525 /* Anything here makes it impossible or too hard
1526 * to calculate the offset -- so we give up;
1527 * save the last known good offset, in case the
1528 * must sequence doesn't occur later.
1530 if (newlen > g->mlen) { /* ends one */
1534 g->moffset += offset;
1536 g->moffset = offset;
1542 } while (OP(s) != OEND);
1544 if (g->mlen == 0) { /* there isn't one */
1549 /* turn it into a character string */
1550 g->must = malloc((size_t)g->mlen + 1);
1551 if (g->must == NULL) { /* argh; just forget it */
1558 memset(&mbs, 0, sizeof(mbs));
1559 while (cp < g->must + g->mlen) {
1560 while (OP(s = *scan++) != OCHAR)
1562 clen = wcrtomb(cp, OPND(s), &mbs);
1563 assert(clen != (size_t)-1);
1566 assert(cp == g->must + g->mlen);
1567 *cp++ = '\0'; /* just on general principles */
1571 - altoffset - choose biggest offset among multiple choices
1572 == static int altoffset(sop *scan, int offset);
1574 * Compute, recursively if necessary, the largest offset among multiple
1578 altoffset(sop *scan, int offset)
1584 /* If we gave up already on offsets, return */
1591 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1600 try = altoffset(scan, try);
1607 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1610 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1611 /* We must skip to the next position, or we'll
1612 * leave altoffset() too early.
1638 return largest+offset;
1642 - computejumps - compute char jumps for BM scan
1643 == static void computejumps(struct parse *p, struct re_guts *g);
1645 * This algorithm assumes g->must exists and is has size greater than
1646 * zero. It's based on the algorithm found on Computer Algorithms by
1649 * A char jump is the number of characters one needs to jump based on
1650 * the value of the character from the text that was mismatched.
1653 computejumps(struct parse *p, struct re_guts *g)
1658 /* Avoid making errors worse */
1662 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1663 if (g->charjump == NULL) /* Not a fatal error */
1665 /* Adjust for signed chars, if necessary */
1666 g->charjump = &g->charjump[-(CHAR_MIN)];
1668 /* If the character does not exist in the pattern, the jump
1669 * is equal to the number of characters in the pattern.
1671 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1672 g->charjump[ch] = g->mlen;
1674 /* If the character does exist, compute the jump that would
1675 * take us to the last character in the pattern equal to it
1676 * (notice that we match right to left, so that last character
1677 * is the first one that would be matched).
1679 for (mindex = 0; mindex < g->mlen; mindex++)
1680 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1684 - computematchjumps - compute match jumps for BM scan
1685 == static void computematchjumps(struct parse *p, struct re_guts *g);
1687 * This algorithm assumes g->must exists and is has size greater than
1688 * zero. It's based on the algorithm found on Computer Algorithms by
1691 * A match jump is the number of characters one needs to advance based
1692 * on the already-matched suffix.
1693 * Notice that all values here are minus (g->mlen-1), because of the way
1694 * the search algorithm works.
1697 computematchjumps(struct parse *p, struct re_guts *g)
1699 int mindex; /* General "must" iterator */
1700 int suffix; /* Keeps track of matching suffix */
1701 int ssuffix; /* Keeps track of suffixes' suffix */
1702 int* pmatches; /* pmatches[k] points to the next i
1703 * such that i+1...mlen is a substring
1704 * of k+1...k+mlen-i-1
1707 /* Avoid making errors worse */
1711 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
1712 if (pmatches == NULL) {
1713 g->matchjump = NULL;
1717 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
1718 if (g->matchjump == NULL) { /* Not a fatal error */
1723 /* Set maximum possible jump for each character in the pattern */
1724 for (mindex = 0; mindex < g->mlen; mindex++)
1725 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1727 /* Compute pmatches[] */
1728 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1729 mindex--, suffix--) {
1730 pmatches[mindex] = suffix;
1732 /* If a mismatch is found, interrupting the substring,
1733 * compute the matchjump for that position. If no
1734 * mismatch is found, then a text substring mismatched
1735 * against the suffix will also mismatch against the
1738 while (suffix < g->mlen
1739 && g->must[mindex] != g->must[suffix]) {
1740 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1741 g->mlen - mindex - 1);
1742 suffix = pmatches[suffix];
1746 /* Compute the matchjump up to the last substring found to jump
1747 * to the beginning of the largest must pattern prefix matching
1750 for (mindex = 0; mindex <= suffix; mindex++)
1751 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1752 g->mlen + suffix - mindex);
1754 ssuffix = pmatches[suffix];
1755 while (suffix < g->mlen) {
1756 while (suffix <= ssuffix && suffix < g->mlen) {
1757 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1758 g->mlen + ssuffix - suffix);
1761 if (suffix < g->mlen)
1762 ssuffix = pmatches[ssuffix];
1769 - pluscount - count + nesting
1770 == static sopno pluscount(struct parse *p, struct re_guts *g);
1772 static sopno /* nesting depth */
1773 pluscount(struct parse *p, struct re_guts *g)
1781 return(0); /* there may not be an OEND */
1783 scan = g->strip + 1;
1791 if (plusnest > maxnest)
1796 } while (OP(s) != OEND);