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
41 #if defined(LIBC_SCCS) && !defined(lint)
42 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
43 #endif /* LIBC_SCCS and not lint */
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
47 #include <sys/types.h>
66 * Branching context, used to keep track of branch state for all of the branch-
67 * aware functions. In addition to keeping track of branch positions for the
68 * p_branch_* functions, we use this to simplify some clumsiness in BREs for
69 * detection of whether ^ is acting as an anchor or being used erroneously and
70 * also for whether we're in a sub-expression or not.
84 * parse structure, passed up and down to avoid global variables and
88 const char *next; /* next character in RE */
89 const char *end; /* end of string (-> NUL normally) */
90 int error; /* has an error been seen? */
91 sop *strip; /* malloced strip */
92 sopno ssize; /* malloced strip size (allocated) */
93 sopno slen; /* malloced strip length (used) */
94 int ncsalloc; /* number of csets allocated */
96 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
97 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
98 sopno pend[NPAREN]; /* -> ) ([0] unused) */
99 bool allowbranch; /* can this expression branch? */
100 bool bre; /* convenience; is this a BRE? */
101 bool (*parse_expr)(struct parse *, struct branchc *);
102 void (*pre_parse)(struct parse *, struct branchc *);
103 void (*post_parse)(struct parse *, struct branchc *);
106 /* ========= begin header generated by ./mkh ========= */
111 /* === regcomp.c === */
112 static bool p_ere_exp(struct parse *p, struct branchc *bc);
113 static void p_str(struct parse *p);
114 static int p_branch_eat_delim(struct parse *p, struct branchc *bc);
115 static void p_branch_ins_offset(struct parse *p, struct branchc *bc);
116 static void p_branch_fix_tail(struct parse *p, struct branchc *bc);
117 static bool p_branch_empty(struct parse *p, struct branchc *bc);
118 static bool p_branch_do(struct parse *p, struct branchc *bc);
119 static void p_bre_pre_parse(struct parse *p, struct branchc *bc);
120 static void p_bre_post_parse(struct parse *p, struct branchc *bc);
121 static void p_re(struct parse *p, int end1, int end2);
122 static bool p_simp_re(struct parse *p, struct branchc *bc);
123 static int p_count(struct parse *p);
124 static void p_bracket(struct parse *p);
125 static void p_b_term(struct parse *p, cset *cs);
126 static void p_b_cclass(struct parse *p, cset *cs);
127 static void p_b_eclass(struct parse *p, cset *cs);
128 static wint_t p_b_symbol(struct parse *p);
129 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
130 static wint_t othercase(wint_t ch);
131 static void bothcases(struct parse *p, wint_t ch);
132 static void ordinary(struct parse *p, wint_t ch);
133 static void nonnewline(struct parse *p);
134 static void repeat(struct parse *p, sopno start, int from, int to);
135 static int seterr(struct parse *p, int e);
136 static cset *allocset(struct parse *p);
137 static void freeset(struct parse *p, cset *cs);
138 static void CHadd(struct parse *p, cset *cs, wint_t ch);
139 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
140 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
141 static wint_t singleton(cset *cs);
142 static sopno dupl(struct parse *p, sopno start, sopno finish);
143 static void doemit(struct parse *p, sop op, size_t opnd);
144 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
145 static void dofwd(struct parse *p, sopno pos, sop value);
146 static int enlarge(struct parse *p, sopno size);
147 static void stripsnug(struct parse *p, struct re_guts *g);
148 static void findmust(struct parse *p, struct re_guts *g);
149 static int altoffset(sop *scan, int offset);
150 static void computejumps(struct parse *p, struct re_guts *g);
151 static void computematchjumps(struct parse *p, struct re_guts *g);
152 static sopno pluscount(struct parse *p, struct re_guts *g);
153 static wint_t wgetnext(struct parse *p);
158 /* ========= end header generated by ./mkh ========= */
160 static char nuls[10]; /* place to point scanner in event of error */
163 * macros for use with parse structure
164 * BEWARE: these know that the parse structure is named `p' !!!
166 #define PEEK() (*p->next)
167 #define PEEK2() (*(p->next+1))
168 #define MORE() (p->next < p->end)
169 #define MORE2() (p->next+1 < p->end)
170 #define SEE(c) (MORE() && PEEK() == (c))
171 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
172 #define SEESPEC(a) (p->bre ? SEETWO('\\', a) : SEE(a))
173 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
174 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
175 #define NEXT() (p->next++)
176 #define NEXT2() (p->next += 2)
177 #define NEXTn(n) (p->next += (n))
178 #define GETNEXT() (*p->next++)
179 #define WGETNEXT() wgetnext(p)
180 #define SETERROR(e) seterr(p, (e))
181 #define REQUIRE(co, e) ((co) || SETERROR(e))
182 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
183 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
184 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
185 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
186 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
187 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
188 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
189 #define HERE() (p->slen)
190 #define THERE() (p->slen - 1)
191 #define THERETHERE() (p->slen - 2)
192 #define DROP(n) (p->slen -= (n))
195 static int never = 0; /* for use in asserts; shuts lint up */
197 #define never 0 /* some <assert.h>s have bugs too */
200 /* Macro used by computejump()/computematchjump() */
201 #define MIN(a,b) ((a)<(b)?(a):(b))
204 - regcomp - interface for parser and compilation
205 = extern int regcomp(regex_t *, const char *, int);
206 = #define REG_BASIC 0000
207 = #define REG_EXTENDED 0001
208 = #define REG_ICASE 0002
209 = #define REG_NOSUB 0004
210 = #define REG_NEWLINE 0010
211 = #define REG_NOSPEC 0020
212 = #define REG_PEND 0040
213 = #define REG_DUMP 0200
215 int /* 0 success, otherwise REG_something */
216 regcomp(regex_t * __restrict preg,
217 const char * __restrict pattern,
222 struct parse *p = &pa;
227 # define GOODFLAGS(f) (f)
229 # define GOODFLAGS(f) ((f)&~REG_DUMP)
232 cflags = GOODFLAGS(cflags);
233 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
236 if (cflags®_PEND) {
237 if (preg->re_endp < pattern)
239 len = preg->re_endp - pattern;
241 len = strlen(pattern);
243 /* do the mallocs early so failure handling is easy */
244 g = (struct re_guts *)malloc(sizeof(struct re_guts));
248 * Limit the pattern space to avoid a 32-bit overflow on buffer
249 * extension. Also avoid any signed overflow in case of conversion
250 * so make the real limit based on a 31-bit overflow.
252 * Likely not applicable on 64-bit systems but handle the case
253 * generically (who are we to stop people from using ~715MB+
256 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
261 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
262 assert(p->ssize >= len);
264 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
266 if (p->strip == NULL) {
273 p->next = pattern; /* convenience; we do not modify it */
274 p->end = p->next + len;
277 for (i = 0; i < NPAREN; i++) {
281 if (cflags & REG_EXTENDED) {
282 p->allowbranch = true;
284 p->parse_expr = p_ere_exp;
286 p->post_parse = NULL;
288 p->allowbranch = false;
290 p->parse_expr = p_simp_re;
291 p->pre_parse = p_bre_pre_parse;
292 p->post_parse = p_bre_post_parse;
310 g->firststate = THERE();
311 if (cflags & REG_NOSPEC)
316 g->laststate = THERE();
318 /* tidy up loose ends and fill things in */
321 /* only use Boyer-Moore algorithm if the pattern is bigger
322 * than three characters
326 computematchjumps(p, g);
327 if(g->matchjump == NULL && g->charjump != NULL) {
332 g->nplus = pluscount(p, g);
334 preg->re_nsub = g->nsub;
336 preg->re_magic = MAGIC1;
338 /* not debugging, so can't rely on the assert() in regexec() */
340 SETERROR(REG_ASSERT);
343 /* win or lose, we're done */
344 if (p->error != 0) /* lose */
350 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op,
351 - return whether we should terminate or not
352 == static bool p_ere_exp(struct parse *p);
355 p_ere_exp(struct parse *p, struct branchc *bc)
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;
416 SETERROR(REG_BADRPT);
419 if (p->g->cflags®_NEWLINE)
428 (void)REQUIRE(MORE(), REG_EESCAPE);
454 /* we call { a repetition if followed by a digit */
455 if (!( c == '*' || c == '+' || c == '?' || c == '{'))
456 return (false); /* no repetition, we're done */
458 (void)REQUIRE(MORE2() && \
459 (isdigit((uch)PEEK2()) || PEEK2() == ','), REG_BADRPT);
462 (void)REQUIRE(!wascaret, REG_BADRPT);
464 case '*': /* implemented as +? */
465 /* this case does not require the (y|) trick, noKLUDGE */
468 INSERT(OQUEST_, pos);
469 ASTERN(O_QUEST, pos);
476 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
477 INSERT(OCH_, pos); /* offset slightly wrong */
478 ASTERN(OOR1, pos); /* this one's right */
479 AHEAD(pos); /* fix the OCH_ */
480 EMIT(OOR2, 0); /* offset very wrong... */
481 AHEAD(THERE()); /* ...so fix it */
482 ASTERN(O_CH, THERETHERE());
487 if (isdigit((uch)PEEK())) {
489 (void)REQUIRE(count <= count2, REG_BADBR);
490 } else /* single number with comma */
492 } else /* just a single number */
494 repeat(p, pos, count, count2);
495 if (!EAT('}')) { /* error heuristics */
496 while (MORE() && PEEK() != '}')
498 (void)REQUIRE(MORE(), REG_EBRACE);
507 if (!( c == '*' || c == '+' || c == '?' ||
508 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
510 SETERROR(REG_BADRPT);
515 - p_str - string (no metacharacters) "parser"
516 == static void p_str(struct parse *p);
519 p_str(struct parse *p)
521 (void)REQUIRE(MORE(), REG_EMPTY);
523 ordinary(p, WGETNEXT());
527 * Eat consecutive branch delimiters for the kind of expression that we are
528 * parsing, return the number of delimiters that we ate.
531 p_branch_eat_delim(struct parse *p, struct branchc *bc)
542 * Insert necessary branch book-keeping operations. This emits a
543 * bogus 'next' offset, since we still have more to parse
546 p_branch_ins_offset(struct parse *p, struct branchc *bc)
549 if (bc->nbranch == 0) {
550 INSERT(OCH_, bc->start); /* offset is wrong */
552 bc->back = bc->start;
555 ASTERN(OOR1, bc->back);
557 AHEAD(bc->fwd); /* fix previous offset */
559 EMIT(OOR2, 0); /* offset is very wrong */
564 * Fix the offset of the tail branch, if we actually had any branches.
565 * This is to correct the bogus placeholder offset that we use.
568 p_branch_fix_tail(struct parse *p, struct branchc *bc)
571 /* Fix bogus offset at the tail if we actually have branches */
572 if (bc->nbranch > 0) {
574 ASTERN(O_CH, bc->back);
579 * Signal to the parser that an empty branch has been encountered; this will,
580 * in the future, be used to allow for more permissive behavior with empty
581 * branches. The return value should indicate whether parsing may continue
585 p_branch_empty(struct parse *p, struct branchc *bc)
593 * Take care of any branching requirements. This includes inserting the
594 * appropriate branching instructions as well as eating all of the branch
595 * delimiters until we either run out of pattern or need to parse more pattern.
598 p_branch_do(struct parse *p, struct branchc *bc)
602 ate = p_branch_eat_delim(p, bc);
605 else if ((ate > 1 || (bc->outer && !MORE())) && !p_branch_empty(p, bc))
607 * Halt parsing only if we have an empty branch and p_branch_empty
608 * indicates that we must not continue. In the future, this will not
609 * necessarily be an error.
612 p_branch_ins_offset(p, bc);
618 p_bre_pre_parse(struct parse *p, struct branchc *bc)
623 * Does not move cleanly into expression parser because of
624 * ordinary interpration of * at the beginning position of
629 p->g->iflags |= USEBOL;
635 p_bre_post_parse(struct parse *p, struct branchc *bc)
638 /* Expression is terminating due to EOL token */
642 p->g->iflags |= USEEOL;
648 - p_re - Top level parser, concatenation and BRE anchoring
649 == static void p_re(struct parse *p, int end1, int end2);
650 * Giving end1 as OUT essentially eliminates the end1/end2 check.
652 * This implementation is a bit of a kludge, in that a trailing $ is first
653 * taken as an ordinary character and then revised to be an anchor.
654 * The amount of lookahead needed to avoid this kludge is excessive.
657 p_re(struct parse *p,
658 int end1, /* first terminating character */
659 int end2) /* second terminating character; ignored for EREs */
664 if (end1 == OUT && end2 == OUT)
668 #define SEEEND() (!p->bre ? SEE(end1) : SEETWO(end1, end2))
672 bc.terminate = false;
673 if (p->pre_parse != NULL)
674 p->pre_parse(p, &bc);
675 while (MORE() && (!p->allowbranch || !SEESPEC('|')) && !SEEEND()) {
676 bc.terminate = p->parse_expr(p, &bc);
679 if (p->post_parse != NULL)
680 p->post_parse(p, &bc);
681 (void) REQUIRE(HERE() != bc.start, REG_EMPTY);
685 * p_branch_do's return value indicates whether we should
686 * continue parsing or not. This is both for correctness and
687 * a slight optimization, because it will check if we've
688 * encountered an empty branch or the end of the string
689 * immediately following a branch delimiter.
691 if (!p_branch_do(p, &bc))
696 p_branch_fix_tail(p, &bc);
697 assert(!MORE() || SEE(end1));
701 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
702 == static bool p_simp_re(struct parse *p, struct branchc *bc);
704 static bool /* was the simple RE an unbackslashed $? */
705 p_simp_re(struct parse *p, struct branchc *bc)
714 # define BACKSL (1<<CHAR_BIT)
716 pos = HERE(); /* repetition op, if any, covers from here */
718 assert(MORE()); /* caller should have ensured this */
721 (void)REQUIRE(MORE(), REG_EESCAPE);
722 c = BACKSL | GETNEXT();
726 if (p->g->cflags®_NEWLINE)
741 SETERROR(REG_BADRPT);
747 p->pbegin[subno] = HERE();
748 EMIT(OLPAREN, subno);
749 /* the MORE here is an error heuristic */
750 if (MORE() && !SEETWO('\\', ')'))
752 if (subno < NPAREN) {
753 p->pend[subno] = HERE();
754 assert(p->pend[subno] != 0);
756 EMIT(ORPAREN, subno);
757 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
759 case BACKSL|')': /* should not get here -- must be user */
760 SETERROR(REG_EPAREN);
771 i = (c&~BACKSL) - '0';
773 if (p->pend[i] != 0) {
774 assert(i <= p->g->nsub);
776 assert(p->pbegin[i] != 0);
777 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
778 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
779 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
782 SETERROR(REG_ESUBREG);
787 * Ordinary if used as the first character beyond BOL anchor of
788 * a (sub-)expression, counts as a bad repetition operator if it
791 (void)REQUIRE(bc->nchain == 0, REG_BADRPT);
795 return (false); /* Definitely not $... */
802 if (EAT('*')) { /* implemented as +? */
803 /* this case does not require the (y|) trick, noKLUDGE */
806 INSERT(OQUEST_, pos);
807 ASTERN(O_QUEST, pos);
808 } else if (EATTWO('\\', '{')) {
811 if (MORE() && isdigit((uch)PEEK())) {
813 (void)REQUIRE(count <= count2, REG_BADBR);
814 } else /* single number with comma */
816 } else /* just a single number */
818 repeat(p, pos, count, count2);
819 if (!EATTWO('\\', '}')) { /* error heuristics */
820 while (MORE() && !SEETWO('\\', '}'))
822 (void)REQUIRE(MORE(), REG_EBRACE);
825 } else if (c == '$') /* $ (but not \$) ends it */
832 - p_count - parse a repetition count
833 == static int p_count(struct parse *p);
835 static int /* the value */
836 p_count(struct parse *p)
841 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
842 count = count*10 + (GETNEXT() - '0');
846 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
851 - p_bracket - parse a bracketed character list
852 == static void p_bracket(struct parse *p);
855 p_bracket(struct parse *p)
860 /* Dept of Truly Sickening Special-Case Kludges */
861 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
866 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
872 if ((cs = allocset(p)) == NULL)
875 if (p->g->cflags®_ICASE)
883 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
887 (void)MUSTEAT(']', REG_EBRACK);
889 if (p->error != 0) /* don't mess things up further */
892 if (cs->invert && p->g->cflags®_NEWLINE)
893 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
895 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
899 EMIT(OANYOF, (int)(cs - p->g->sets));
903 - p_b_term - parse one term of a bracketed character list
904 == static void p_b_term(struct parse *p, cset *cs);
907 p_b_term(struct parse *p, cset *cs)
910 wint_t start, finish;
912 struct xlocale_collate *table =
913 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
915 /* classify what we've got */
916 switch ((MORE()) ? PEEK() : '\0') {
918 c = (MORE2()) ? PEEK2() : '\0';
921 SETERROR(REG_ERANGE);
922 return; /* NOTE RETURN */
929 case ':': /* character class */
931 (void)REQUIRE(MORE(), REG_EBRACK);
933 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
935 (void)REQUIRE(MORE(), REG_EBRACK);
936 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
938 case '=': /* equivalence class */
940 (void)REQUIRE(MORE(), REG_EBRACK);
942 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
944 (void)REQUIRE(MORE(), REG_EBRACK);
945 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
947 default: /* symbol, ordinary character, or range */
948 start = p_b_symbol(p);
949 if (SEE('-') && MORE2() && PEEK2() != ']') {
955 finish = p_b_symbol(p);
961 if (table->__collate_load_error || MB_CUR_MAX > 1) {
962 (void)REQUIRE(start <= finish, REG_ERANGE);
963 CHaddrange(p, cs, start, finish);
965 (void)REQUIRE(__wcollate_range_cmp(start, finish) <= 0, REG_ERANGE);
966 for (i = 0; i <= UCHAR_MAX; i++) {
967 if ( __wcollate_range_cmp(start, i) <= 0
968 && __wcollate_range_cmp(i, finish) <= 0
979 - p_b_cclass - parse a character-class name and deal with it
980 == static void p_b_cclass(struct parse *p, cset *cs);
983 p_b_cclass(struct parse *p, cset *cs)
985 const char *sp = p->next;
990 while (MORE() && isalpha((uch)PEEK()))
993 if (len >= sizeof(clname) - 1) {
994 SETERROR(REG_ECTYPE);
997 memcpy(clname, sp, len);
999 if ((wct = wctype(clname)) == 0) {
1000 SETERROR(REG_ECTYPE);
1003 CHaddtype(p, cs, wct);
1007 - p_b_eclass - parse an equivalence-class name and deal with it
1008 == static void p_b_eclass(struct parse *p, cset *cs);
1010 * This implementation is incomplete. xxx
1013 p_b_eclass(struct parse *p, cset *cs)
1017 c = p_b_coll_elem(p, '=');
1022 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
1023 == static wint_t p_b_symbol(struct parse *p);
1025 static wint_t /* value of symbol */
1026 p_b_symbol(struct parse *p)
1030 (void)REQUIRE(MORE(), REG_EBRACK);
1031 if (!EATTWO('[', '.'))
1034 /* collating symbol */
1035 value = p_b_coll_elem(p, '.');
1036 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1041 - p_b_coll_elem - parse a collating-element name and look it up
1042 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
1044 static wint_t /* value of collating element */
1045 p_b_coll_elem(struct parse *p,
1046 wint_t endc) /* name ended by endc,']' */
1048 const char *sp = p->next;
1054 while (MORE() && !SEETWO(endc, ']'))
1057 SETERROR(REG_EBRACK);
1061 for (cp = cnames; cp->name != NULL; cp++)
1062 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1063 return(cp->code); /* known name */
1064 memset(&mbs, 0, sizeof(mbs));
1065 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
1066 return (wc); /* single character */
1067 else if (clen == (size_t)-1 || clen == (size_t)-2)
1068 SETERROR(REG_ILLSEQ);
1070 SETERROR(REG_ECOLLATE); /* neither */
1075 - othercase - return the case counterpart of an alphabetic
1076 == static wint_t othercase(wint_t ch);
1078 static wint_t /* if no counterpart, return ch */
1079 othercase(wint_t ch)
1081 assert(iswalpha(ch));
1083 return(towlower(ch));
1084 else if (iswlower(ch))
1085 return(towupper(ch));
1086 else /* peculiar, but could happen */
1091 - bothcases - emit a dualcase version of a two-case character
1092 == static void bothcases(struct parse *p, wint_t ch);
1094 * Boy, is this implementation ever a kludge...
1097 bothcases(struct parse *p, wint_t ch)
1099 const char *oldnext = p->next;
1100 const char *oldend = p->end;
1101 char bracket[3 + MB_LEN_MAX];
1105 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1107 memset(&mbs, 0, sizeof(mbs));
1108 n = wcrtomb(bracket, ch, &mbs);
1109 assert(n != (size_t)-1);
1111 bracket[n + 1] = '\0';
1112 p->end = bracket+n+1;
1114 assert(p->next == p->end);
1120 - ordinary - emit an ordinary character
1121 == static void ordinary(struct parse *p, wint_t ch);
1124 ordinary(struct parse *p, wint_t ch)
1128 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
1130 else if ((ch & OPDMASK) == ch)
1134 * Kludge: character is too big to fit into an OCHAR operand.
1135 * Emit a singleton set.
1137 if ((cs = allocset(p)) == NULL)
1140 EMIT(OANYOF, (int)(cs - p->g->sets));
1145 - nonnewline - emit REG_NEWLINE version of OANY
1146 == static void nonnewline(struct parse *p);
1148 * Boy, is this implementation ever a kludge...
1151 nonnewline(struct parse *p)
1153 const char *oldnext = p->next;
1154 const char *oldend = p->end;
1164 assert(p->next == bracket+3);
1170 - repeat - generate code for a bounded repetition, recursively if needed
1171 == static void repeat(struct parse *p, sopno start, int from, int to);
1174 repeat(struct parse *p,
1175 sopno start, /* operand from here to end of strip */
1176 int from, /* repeated from this number */
1177 int to) /* to this number of times (maybe INFINITY) */
1179 sopno finish = HERE();
1182 # define REP(f, t) ((f)*8 + (t))
1183 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1186 if (p->error != 0) /* head off possible runaway recursion */
1191 switch (REP(MAP(from), MAP(to))) {
1192 case REP(0, 0): /* must be user doing this */
1193 DROP(finish-start); /* drop the operand */
1195 case REP(0, 1): /* as x{1,1}? */
1196 case REP(0, N): /* as x{1,n}? */
1197 case REP(0, INF): /* as x{1,}? */
1198 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1199 INSERT(OCH_, start); /* offset is wrong... */
1200 repeat(p, start+1, 1, to);
1201 ASTERN(OOR1, start);
1202 AHEAD(start); /* ... fix it */
1205 ASTERN(O_CH, THERETHERE());
1207 case REP(1, 1): /* trivial case */
1210 case REP(1, N): /* as x?x{1,n-1} */
1211 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1212 INSERT(OCH_, start);
1213 ASTERN(OOR1, start);
1215 EMIT(OOR2, 0); /* offset very wrong... */
1216 AHEAD(THERE()); /* ...so fix it */
1217 ASTERN(O_CH, THERETHERE());
1218 copy = dupl(p, start+1, finish+1);
1219 assert(copy == finish+4);
1220 repeat(p, copy, 1, to-1);
1222 case REP(1, INF): /* as x+ */
1223 INSERT(OPLUS_, start);
1224 ASTERN(O_PLUS, start);
1226 case REP(N, N): /* as xx{m-1,n-1} */
1227 copy = dupl(p, start, finish);
1228 repeat(p, copy, from-1, to-1);
1230 case REP(N, INF): /* as xx{n-1,INF} */
1231 copy = dupl(p, start, finish);
1232 repeat(p, copy, from-1, to);
1234 default: /* "can't happen" */
1235 SETERROR(REG_ASSERT); /* just in case */
1241 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1242 - character from the parse struct, signals a REG_ILLSEQ error if the
1243 - character can't be converted. Returns the number of bytes consumed.
1246 wgetnext(struct parse *p)
1252 memset(&mbs, 0, sizeof(mbs));
1253 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1254 if (n == (size_t)-1 || n == (size_t)-2) {
1255 SETERROR(REG_ILLSEQ);
1265 - seterr - set an error condition
1266 == static int seterr(struct parse *p, int e);
1268 static int /* useless but makes type checking happy */
1269 seterr(struct parse *p, int e)
1271 if (p->error == 0) /* keep earliest error condition */
1273 p->next = nuls; /* try to bring things to a halt */
1275 return(0); /* make the return value well-defined */
1279 - allocset - allocate a set of characters for []
1280 == static cset *allocset(struct parse *p);
1283 allocset(struct parse *p)
1287 ncs = reallocarray(p->g->sets, p->g->ncsets + 1, sizeof(*ncs));
1289 SETERROR(REG_ESPACE);
1293 cs = &p->g->sets[p->g->ncsets++];
1294 memset(cs, 0, sizeof(*cs));
1300 - freeset - free a now-unused set
1301 == static void freeset(struct parse *p, cset *cs);
1304 freeset(struct parse *p, cset *cs)
1306 cset *top = &p->g->sets[p->g->ncsets];
1311 memset(cs, 0, sizeof(*cs));
1312 if (cs == top-1) /* recover only the easy case */
1317 - singleton - Determine whether a set contains only one character,
1318 - returning it if so, otherwise returning OUT.
1325 for (i = n = 0; i < NC; i++)
1332 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1334 return (cs->wides[0]);
1335 /* Don't bother handling the other cases. */
1340 - CHadd - add character to character set.
1343 CHadd(struct parse *p, cset *cs, wint_t ch)
1345 wint_t nch, *newwides;
1348 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1350 newwides = reallocarray(cs->wides, cs->nwides + 1,
1351 sizeof(*cs->wides));
1352 if (newwides == NULL) {
1353 SETERROR(REG_ESPACE);
1356 cs->wides = newwides;
1357 cs->wides[cs->nwides++] = ch;
1360 if ((nch = towlower(ch)) < NC)
1361 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1362 if ((nch = towupper(ch)) < NC)
1363 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1368 - CHaddrange - add all characters in the range [min,max] to a character set.
1371 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1375 for (; min < NC && min <= max; min++)
1379 newranges = reallocarray(cs->ranges, cs->nranges + 1,
1380 sizeof(*cs->ranges));
1381 if (newranges == NULL) {
1382 SETERROR(REG_ESPACE);
1385 cs->ranges = newranges;
1386 cs->ranges[cs->nranges].min = min;
1387 cs->ranges[cs->nranges].max = max;
1392 - CHaddtype - add all characters of a certain type to a character set.
1395 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1400 for (i = 0; i < NC; i++)
1401 if (iswctype(i, wct))
1403 newtypes = reallocarray(cs->types, cs->ntypes + 1,
1404 sizeof(*cs->types));
1405 if (newtypes == NULL) {
1406 SETERROR(REG_ESPACE);
1409 cs->types = newtypes;
1410 cs->types[cs->ntypes++] = wct;
1414 - dupl - emit a duplicate of a bunch of sops
1415 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1417 static sopno /* start of duplicate */
1418 dupl(struct parse *p,
1419 sopno start, /* from here */
1420 sopno finish) /* to this less one */
1423 sopno len = finish - start;
1425 assert(finish >= start);
1428 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1430 (void) memcpy((char *)(p->strip + p->slen),
1431 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1437 - doemit - emit a strip operator
1438 == static void doemit(struct parse *p, sop op, size_t opnd);
1440 * It might seem better to implement this as a macro with a function as
1441 * hard-case backup, but it's just too big and messy unless there are
1442 * some changes to the data structures. Maybe later.
1445 doemit(struct parse *p, sop op, size_t opnd)
1447 /* avoid making error situations worse */
1451 /* deal with oversize operands ("can't happen", more or less) */
1452 assert(opnd < 1<<OPSHIFT);
1454 /* deal with undersized strip */
1455 if (p->slen >= p->ssize)
1456 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1459 /* finally, it's all reduced to the easy case */
1460 p->strip[p->slen++] = SOP(op, opnd);
1464 - doinsert - insert a sop into the strip
1465 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1468 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1474 /* avoid making error situations worse */
1479 EMIT(op, opnd); /* do checks, ensure space */
1480 assert(HERE() == sn+1);
1483 /* adjust paren pointers */
1485 for (i = 1; i < NPAREN; i++) {
1486 if (p->pbegin[i] >= pos) {
1489 if (p->pend[i] >= pos) {
1494 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1495 (HERE()-pos-1)*sizeof(sop));
1500 - dofwd - complete a forward reference
1501 == static void dofwd(struct parse *p, sopno pos, sop value);
1504 dofwd(struct parse *p, sopno pos, sop value)
1506 /* avoid making error situations worse */
1510 assert(value < 1<<OPSHIFT);
1511 p->strip[pos] = OP(p->strip[pos]) | value;
1515 - enlarge - enlarge the strip
1516 == static int enlarge(struct parse *p, sopno size);
1519 enlarge(struct parse *p, sopno size)
1523 if (p->ssize >= size)
1526 sp = reallocarray(p->strip, size, sizeof(sop));
1528 SETERROR(REG_ESPACE);
1537 - stripsnug - compact the strip
1538 == static void stripsnug(struct parse *p, struct re_guts *g);
1541 stripsnug(struct parse *p, struct re_guts *g)
1543 g->nstates = p->slen;
1544 g->strip = reallocarray((char *)p->strip, p->slen, sizeof(sop));
1545 if (g->strip == NULL) {
1546 SETERROR(REG_ESPACE);
1547 g->strip = p->strip;
1552 - findmust - fill in must and mlen with longest mandatory literal string
1553 == static void findmust(struct parse *p, struct re_guts *g);
1555 * This algorithm could do fancy things like analyzing the operands of |
1556 * for common subsequences. Someday. This code is simple and finds most
1557 * of the interesting cases.
1559 * Note that must and mlen got initialized during setup.
1562 findmust(struct parse *p, struct re_guts *g)
1566 sop *newstart = NULL;
1571 char buf[MB_LEN_MAX];
1575 /* avoid making error situations worse */
1580 * It's not generally safe to do a ``char'' substring search on
1581 * multibyte character strings, but it's safe for at least
1582 * UTF-8 (see RFC 3629).
1584 if (MB_CUR_MAX > 1 &&
1585 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1588 /* find the longest OCHAR sequence in strip */
1592 scan = g->strip + 1;
1596 case OCHAR: /* sequence member */
1597 if (newlen == 0) { /* new sequence */
1598 memset(&mbs, 0, sizeof(mbs));
1599 newstart = scan - 1;
1601 clen = wcrtomb(buf, OPND(s), &mbs);
1602 if (clen == (size_t)-1)
1606 case OPLUS_: /* things that don't break one */
1610 case OQUEST_: /* things that must be skipped */
1612 offset = altoffset(scan, offset);
1617 /* assert() interferes w debug printouts */
1618 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1623 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1625 case OBOW: /* things that break a sequence */
1632 if (newlen > g->mlen) { /* ends one */
1636 g->moffset += offset;
1639 g->moffset = offset;
1647 if (newlen > g->mlen) { /* ends one */
1651 g->moffset += offset;
1654 g->moffset = offset;
1663 case OANYOF: /* may or may not invalidate offset */
1664 /* First, everything as OANY */
1665 if (newlen > g->mlen) { /* ends one */
1669 g->moffset += offset;
1672 g->moffset = offset;
1683 /* Anything here makes it impossible or too hard
1684 * to calculate the offset -- so we give up;
1685 * save the last known good offset, in case the
1686 * must sequence doesn't occur later.
1688 if (newlen > g->mlen) { /* ends one */
1692 g->moffset += offset;
1694 g->moffset = offset;
1700 } while (OP(s) != OEND);
1702 if (g->mlen == 0) { /* there isn't one */
1707 /* turn it into a character string */
1708 g->must = malloc((size_t)g->mlen + 1);
1709 if (g->must == NULL) { /* argh; just forget it */
1716 memset(&mbs, 0, sizeof(mbs));
1717 while (cp < g->must + g->mlen) {
1718 while (OP(s = *scan++) != OCHAR)
1720 clen = wcrtomb(cp, OPND(s), &mbs);
1721 assert(clen != (size_t)-1);
1724 assert(cp == g->must + g->mlen);
1725 *cp++ = '\0'; /* just on general principles */
1729 - altoffset - choose biggest offset among multiple choices
1730 == static int altoffset(sop *scan, int offset);
1732 * Compute, recursively if necessary, the largest offset among multiple
1736 altoffset(sop *scan, int offset)
1742 /* If we gave up already on offsets, return */
1749 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1758 try = altoffset(scan, try);
1765 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1768 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1769 /* We must skip to the next position, or we'll
1770 * leave altoffset() too early.
1796 return largest+offset;
1800 - computejumps - compute char jumps for BM scan
1801 == static void computejumps(struct parse *p, struct re_guts *g);
1803 * This algorithm assumes g->must exists and is has size greater than
1804 * zero. It's based on the algorithm found on Computer Algorithms by
1807 * A char jump is the number of characters one needs to jump based on
1808 * the value of the character from the text that was mismatched.
1811 computejumps(struct parse *p, struct re_guts *g)
1816 /* Avoid making errors worse */
1820 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1821 if (g->charjump == NULL) /* Not a fatal error */
1823 /* Adjust for signed chars, if necessary */
1824 g->charjump = &g->charjump[-(CHAR_MIN)];
1826 /* If the character does not exist in the pattern, the jump
1827 * is equal to the number of characters in the pattern.
1829 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1830 g->charjump[ch] = g->mlen;
1832 /* If the character does exist, compute the jump that would
1833 * take us to the last character in the pattern equal to it
1834 * (notice that we match right to left, so that last character
1835 * is the first one that would be matched).
1837 for (mindex = 0; mindex < g->mlen; mindex++)
1838 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1842 - computematchjumps - compute match jumps for BM scan
1843 == static void computematchjumps(struct parse *p, struct re_guts *g);
1845 * This algorithm assumes g->must exists and is has size greater than
1846 * zero. It's based on the algorithm found on Computer Algorithms by
1849 * A match jump is the number of characters one needs to advance based
1850 * on the already-matched suffix.
1851 * Notice that all values here are minus (g->mlen-1), because of the way
1852 * the search algorithm works.
1855 computematchjumps(struct parse *p, struct re_guts *g)
1857 int mindex; /* General "must" iterator */
1858 int suffix; /* Keeps track of matching suffix */
1859 int ssuffix; /* Keeps track of suffixes' suffix */
1860 int* pmatches; /* pmatches[k] points to the next i
1861 * such that i+1...mlen is a substring
1862 * of k+1...k+mlen-i-1
1865 /* Avoid making errors worse */
1869 pmatches = (int*) malloc(g->mlen * sizeof(int));
1870 if (pmatches == NULL) {
1871 g->matchjump = NULL;
1875 g->matchjump = (int*) malloc(g->mlen * sizeof(int));
1876 if (g->matchjump == NULL) { /* Not a fatal error */
1881 /* Set maximum possible jump for each character in the pattern */
1882 for (mindex = 0; mindex < g->mlen; mindex++)
1883 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1885 /* Compute pmatches[] */
1886 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1887 mindex--, suffix--) {
1888 pmatches[mindex] = suffix;
1890 /* If a mismatch is found, interrupting the substring,
1891 * compute the matchjump for that position. If no
1892 * mismatch is found, then a text substring mismatched
1893 * against the suffix will also mismatch against the
1896 while (suffix < g->mlen
1897 && g->must[mindex] != g->must[suffix]) {
1898 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1899 g->mlen - mindex - 1);
1900 suffix = pmatches[suffix];
1904 /* Compute the matchjump up to the last substring found to jump
1905 * to the beginning of the largest must pattern prefix matching
1908 for (mindex = 0; mindex <= suffix; mindex++)
1909 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1910 g->mlen + suffix - mindex);
1912 ssuffix = pmatches[suffix];
1913 while (suffix < g->mlen) {
1914 while (suffix <= ssuffix && suffix < g->mlen) {
1915 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1916 g->mlen + ssuffix - suffix);
1919 if (suffix < g->mlen)
1920 ssuffix = pmatches[ssuffix];
1927 - pluscount - count + nesting
1928 == static sopno pluscount(struct parse *p, struct re_guts *g);
1930 static sopno /* nesting depth */
1931 pluscount(struct parse *p, struct re_guts *g)
1939 return(0); /* there may not be an OEND */
1941 scan = g->strip + 1;
1949 if (plusnest > maxnest)
1954 } while (OP(s) != OEND);