2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
5 * Copyright (c) 1992, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 2011 The FreeBSD Foundation
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
13 * This code is derived from software contributed to Berkeley by
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
43 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
45 #endif /* LIBC_SCCS and not lint */
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 #include <sys/types.h>
68 * Branching context, used to keep track of branch state for all of the branch-
69 * aware functions. In addition to keeping track of branch positions for the
70 * p_branch_* functions, we use this to simplify some clumsiness in BREs for
71 * detection of whether ^ is acting as an anchor or being used erroneously and
72 * also for whether we're in a sub-expression or not.
86 * parse structure, passed up and down to avoid global variables and
90 const char *next; /* next character in RE */
91 const char *end; /* end of string (-> NUL normally) */
92 int error; /* has an error been seen? */
93 sop *strip; /* malloced strip */
94 sopno ssize; /* malloced strip size (allocated) */
95 sopno slen; /* malloced strip length (used) */
96 int ncsalloc; /* number of csets allocated */
98 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
99 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
100 sopno pend[NPAREN]; /* -> ) ([0] unused) */
101 bool allowbranch; /* can this expression branch? */
102 bool bre; /* convenience; is this a BRE? */
103 bool (*parse_expr)(struct parse *, struct branchc *);
104 void (*pre_parse)(struct parse *, struct branchc *);
105 void (*post_parse)(struct parse *, struct branchc *);
108 /* ========= begin header generated by ./mkh ========= */
113 /* === regcomp.c === */
114 static bool p_ere_exp(struct parse *p, struct branchc *bc);
115 static void p_str(struct parse *p);
116 static int p_branch_eat_delim(struct parse *p, struct branchc *bc);
117 static void p_branch_ins_offset(struct parse *p, struct branchc *bc);
118 static void p_branch_fix_tail(struct parse *p, struct branchc *bc);
119 static bool p_branch_empty(struct parse *p, struct branchc *bc);
120 static bool p_branch_do(struct parse *p, struct branchc *bc);
121 static void p_bre_pre_parse(struct parse *p, struct branchc *bc);
122 static void p_bre_post_parse(struct parse *p, struct branchc *bc);
123 static void p_re(struct parse *p, int end1, int end2);
124 static bool p_simp_re(struct parse *p, struct branchc *bc);
125 static int p_count(struct parse *p);
126 static void p_bracket(struct parse *p);
127 static void p_b_term(struct parse *p, cset *cs);
128 static void p_b_cclass(struct parse *p, cset *cs);
129 static void p_b_eclass(struct parse *p, cset *cs);
130 static wint_t p_b_symbol(struct parse *p);
131 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
132 static wint_t othercase(wint_t ch);
133 static void bothcases(struct parse *p, wint_t ch);
134 static void ordinary(struct parse *p, wint_t ch);
135 static void nonnewline(struct parse *p);
136 static void repeat(struct parse *p, sopno start, int from, int to);
137 static int seterr(struct parse *p, int e);
138 static cset *allocset(struct parse *p);
139 static void freeset(struct parse *p, cset *cs);
140 static void CHadd(struct parse *p, cset *cs, wint_t ch);
141 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
142 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
143 static wint_t singleton(cset *cs);
144 static sopno dupl(struct parse *p, sopno start, sopno finish);
145 static void doemit(struct parse *p, sop op, size_t opnd);
146 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
147 static void dofwd(struct parse *p, sopno pos, sop value);
148 static int enlarge(struct parse *p, sopno size);
149 static void stripsnug(struct parse *p, struct re_guts *g);
150 static void findmust(struct parse *p, struct re_guts *g);
151 static int altoffset(sop *scan, int offset);
152 static void computejumps(struct parse *p, struct re_guts *g);
153 static void computematchjumps(struct parse *p, struct re_guts *g);
154 static sopno pluscount(struct parse *p, struct re_guts *g);
155 static wint_t wgetnext(struct parse *p);
160 /* ========= end header generated by ./mkh ========= */
162 static char nuls[10]; /* place to point scanner in event of error */
165 * macros for use with parse structure
166 * BEWARE: these know that the parse structure is named `p' !!!
168 #define PEEK() (*p->next)
169 #define PEEK2() (*(p->next+1))
170 #define MORE() (p->next < p->end)
171 #define MORE2() (p->next+1 < p->end)
172 #define SEE(c) (MORE() && PEEK() == (c))
173 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
174 #define SEESPEC(a) (p->bre ? SEETWO('\\', a) : SEE(a))
175 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
176 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
177 #define NEXT() (p->next++)
178 #define NEXT2() (p->next += 2)
179 #define NEXTn(n) (p->next += (n))
180 #define GETNEXT() (*p->next++)
181 #define WGETNEXT() wgetnext(p)
182 #define SETERROR(e) seterr(p, (e))
183 #define REQUIRE(co, e) ((co) || SETERROR(e))
184 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
185 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
186 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
187 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
188 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
189 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
190 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
191 #define HERE() (p->slen)
192 #define THERE() (p->slen - 1)
193 #define THERETHERE() (p->slen - 2)
194 #define DROP(n) (p->slen -= (n))
197 static int never = 0; /* for use in asserts; shuts lint up */
199 #define never 0 /* some <assert.h>s have bugs too */
202 /* Macro used by computejump()/computematchjump() */
203 #define MIN(a,b) ((a)<(b)?(a):(b))
206 - regcomp - interface for parser and compilation
207 = extern int regcomp(regex_t *, const char *, int);
208 = #define REG_BASIC 0000
209 = #define REG_EXTENDED 0001
210 = #define REG_ICASE 0002
211 = #define REG_NOSUB 0004
212 = #define REG_NEWLINE 0010
213 = #define REG_NOSPEC 0020
214 = #define REG_PEND 0040
215 = #define REG_DUMP 0200
217 int /* 0 success, otherwise REG_something */
218 regcomp(regex_t * __restrict preg,
219 const char * __restrict pattern,
224 struct parse *p = &pa;
229 # define GOODFLAGS(f) (f)
231 # define GOODFLAGS(f) ((f)&~REG_DUMP)
234 cflags = GOODFLAGS(cflags);
235 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
238 if (cflags®_PEND) {
239 if (preg->re_endp < pattern)
241 len = preg->re_endp - pattern;
243 len = strlen(pattern);
245 /* do the mallocs early so failure handling is easy */
246 g = (struct re_guts *)malloc(sizeof(struct re_guts));
250 * Limit the pattern space to avoid a 32-bit overflow on buffer
251 * extension. Also avoid any signed overflow in case of conversion
252 * so make the real limit based on a 31-bit overflow.
254 * Likely not applicable on 64-bit systems but handle the case
255 * generically (who are we to stop people from using ~715MB+
258 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
263 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
264 assert(p->ssize >= len);
266 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
268 if (p->strip == NULL) {
275 p->next = pattern; /* convenience; we do not modify it */
276 p->end = p->next + len;
279 for (i = 0; i < NPAREN; i++) {
283 if (cflags & REG_EXTENDED) {
284 p->allowbranch = true;
286 p->parse_expr = p_ere_exp;
288 p->post_parse = NULL;
290 p->allowbranch = false;
292 p->parse_expr = p_simp_re;
293 p->pre_parse = p_bre_pre_parse;
294 p->post_parse = p_bre_post_parse;
312 g->firststate = THERE();
313 if (cflags & REG_NOSPEC)
318 g->laststate = THERE();
320 /* tidy up loose ends and fill things in */
323 /* only use Boyer-Moore algorithm if the pattern is bigger
324 * than three characters
328 computematchjumps(p, g);
329 if(g->matchjump == NULL && g->charjump != NULL) {
334 g->nplus = pluscount(p, g);
336 preg->re_nsub = g->nsub;
338 preg->re_magic = MAGIC1;
340 /* not debugging, so can't rely on the assert() in regexec() */
342 SETERROR(REG_ASSERT);
345 /* win or lose, we're done */
346 if (p->error != 0) /* lose */
352 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op,
353 - return whether we should terminate or not
354 == static bool p_ere_exp(struct parse *p);
357 p_ere_exp(struct parse *p, struct branchc *bc)
367 assert(MORE()); /* caller should have ensured this */
373 (void)REQUIRE(MORE(), REG_EPAREN);
377 p->pbegin[subno] = HERE();
378 EMIT(OLPAREN, subno);
381 if (subno < NPAREN) {
382 p->pend[subno] = HERE();
383 assert(p->pend[subno] != 0);
385 EMIT(ORPAREN, subno);
386 (void)MUSTEAT(')', REG_EPAREN);
388 #ifndef POSIX_MISTAKE
389 case ')': /* happens only if no current unmatched ( */
391 * You may ask, why the ifndef? Because I didn't notice
392 * this until slightly too late for 1003.2, and none of the
393 * other 1003.2 regular-expression reviewers noticed it at
394 * all. So an unmatched ) is legal POSIX, at least until
395 * we can get it fixed.
397 SETERROR(REG_EPAREN);
402 p->g->iflags |= USEBOL;
408 p->g->iflags |= USEEOL;
418 SETERROR(REG_BADRPT);
421 if (p->g->cflags®_NEWLINE)
430 (void)REQUIRE(MORE(), REG_EESCAPE);
456 /* we call { a repetition if followed by a digit */
457 if (!( c == '*' || c == '+' || c == '?' || c == '{'))
458 return (false); /* no repetition, we're done */
460 (void)REQUIRE(MORE2() && \
461 (isdigit((uch)PEEK2()) || PEEK2() == ','), REG_BADRPT);
464 (void)REQUIRE(!wascaret, REG_BADRPT);
466 case '*': /* implemented as +? */
467 /* this case does not require the (y|) trick, noKLUDGE */
470 INSERT(OQUEST_, pos);
471 ASTERN(O_QUEST, pos);
478 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
479 INSERT(OCH_, pos); /* offset slightly wrong */
480 ASTERN(OOR1, pos); /* this one's right */
481 AHEAD(pos); /* fix the OCH_ */
482 EMIT(OOR2, 0); /* offset very wrong... */
483 AHEAD(THERE()); /* ...so fix it */
484 ASTERN(O_CH, THERETHERE());
489 if (isdigit((uch)PEEK())) {
491 (void)REQUIRE(count <= count2, REG_BADBR);
492 } else /* single number with comma */
494 } else /* just a single number */
496 repeat(p, pos, count, count2);
497 if (!EAT('}')) { /* error heuristics */
498 while (MORE() && PEEK() != '}')
500 (void)REQUIRE(MORE(), REG_EBRACE);
509 if (!( c == '*' || c == '+' || c == '?' ||
510 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
512 SETERROR(REG_BADRPT);
517 - p_str - string (no metacharacters) "parser"
518 == static void p_str(struct parse *p);
521 p_str(struct parse *p)
523 (void)REQUIRE(MORE(), REG_EMPTY);
525 ordinary(p, WGETNEXT());
529 * Eat consecutive branch delimiters for the kind of expression that we are
530 * parsing, return the number of delimiters that we ate.
533 p_branch_eat_delim(struct parse *p, struct branchc *bc)
544 * Insert necessary branch book-keeping operations. This emits a
545 * bogus 'next' offset, since we still have more to parse
548 p_branch_ins_offset(struct parse *p, struct branchc *bc)
551 if (bc->nbranch == 0) {
552 INSERT(OCH_, bc->start); /* offset is wrong */
554 bc->back = bc->start;
557 ASTERN(OOR1, bc->back);
559 AHEAD(bc->fwd); /* fix previous offset */
561 EMIT(OOR2, 0); /* offset is very wrong */
566 * Fix the offset of the tail branch, if we actually had any branches.
567 * This is to correct the bogus placeholder offset that we use.
570 p_branch_fix_tail(struct parse *p, struct branchc *bc)
573 /* Fix bogus offset at the tail if we actually have branches */
574 if (bc->nbranch > 0) {
576 ASTERN(O_CH, bc->back);
581 * Signal to the parser that an empty branch has been encountered; this will,
582 * in the future, be used to allow for more permissive behavior with empty
583 * branches. The return value should indicate whether parsing may continue
587 p_branch_empty(struct parse *p, struct branchc *bc)
595 * Take care of any branching requirements. This includes inserting the
596 * appropriate branching instructions as well as eating all of the branch
597 * delimiters until we either run out of pattern or need to parse more pattern.
600 p_branch_do(struct parse *p, struct branchc *bc)
604 ate = p_branch_eat_delim(p, bc);
607 else if ((ate > 1 || (bc->outer && !MORE())) && !p_branch_empty(p, bc))
609 * Halt parsing only if we have an empty branch and p_branch_empty
610 * indicates that we must not continue. In the future, this will not
611 * necessarily be an error.
614 p_branch_ins_offset(p, bc);
620 p_bre_pre_parse(struct parse *p, struct branchc *bc)
625 * Does not move cleanly into expression parser because of
626 * ordinary interpration of * at the beginning position of
631 p->g->iflags |= USEBOL;
637 p_bre_post_parse(struct parse *p, struct branchc *bc)
640 /* Expression is terminating due to EOL token */
644 p->g->iflags |= USEEOL;
650 - p_re - Top level parser, concatenation and BRE anchoring
651 == static void p_re(struct parse *p, int end1, int end2);
652 * Giving end1 as OUT essentially eliminates the end1/end2 check.
654 * This implementation is a bit of a kludge, in that a trailing $ is first
655 * taken as an ordinary character and then revised to be an anchor.
656 * The amount of lookahead needed to avoid this kludge is excessive.
659 p_re(struct parse *p,
660 int end1, /* first terminating character */
661 int end2) /* second terminating character; ignored for EREs */
666 if (end1 == OUT && end2 == OUT)
670 #define SEEEND() (!p->bre ? SEE(end1) : SEETWO(end1, end2))
674 bc.terminate = false;
675 if (p->pre_parse != NULL)
676 p->pre_parse(p, &bc);
677 while (MORE() && (!p->allowbranch || !SEESPEC('|')) && !SEEEND()) {
678 bc.terminate = p->parse_expr(p, &bc);
681 if (p->post_parse != NULL)
682 p->post_parse(p, &bc);
683 (void) REQUIRE(HERE() != bc.start, REG_EMPTY);
687 * p_branch_do's return value indicates whether we should
688 * continue parsing or not. This is both for correctness and
689 * a slight optimization, because it will check if we've
690 * encountered an empty branch or the end of the string
691 * immediately following a branch delimiter.
693 if (!p_branch_do(p, &bc))
698 p_branch_fix_tail(p, &bc);
699 assert(!MORE() || SEE(end1));
703 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
704 == static bool p_simp_re(struct parse *p, struct branchc *bc);
706 static bool /* was the simple RE an unbackslashed $? */
707 p_simp_re(struct parse *p, struct branchc *bc)
716 # define BACKSL (1<<CHAR_BIT)
718 pos = HERE(); /* repetition op, if any, covers from here */
720 assert(MORE()); /* caller should have ensured this */
723 (void)REQUIRE(MORE(), REG_EESCAPE);
724 c = BACKSL | GETNEXT();
728 if (p->g->cflags®_NEWLINE)
743 SETERROR(REG_BADRPT);
749 p->pbegin[subno] = HERE();
750 EMIT(OLPAREN, subno);
751 /* the MORE here is an error heuristic */
752 if (MORE() && !SEETWO('\\', ')'))
754 if (subno < NPAREN) {
755 p->pend[subno] = HERE();
756 assert(p->pend[subno] != 0);
758 EMIT(ORPAREN, subno);
759 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
761 case BACKSL|')': /* should not get here -- must be user */
762 SETERROR(REG_EPAREN);
773 i = (c&~BACKSL) - '0';
775 if (p->pend[i] != 0) {
776 assert(i <= p->g->nsub);
778 assert(p->pbegin[i] != 0);
779 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
780 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
781 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
784 SETERROR(REG_ESUBREG);
789 * Ordinary if used as the first character beyond BOL anchor of
790 * a (sub-)expression, counts as a bad repetition operator if it
793 (void)REQUIRE(bc->nchain == 0, REG_BADRPT);
797 return (false); /* Definitely not $... */
804 if (EAT('*')) { /* implemented as +? */
805 /* this case does not require the (y|) trick, noKLUDGE */
808 INSERT(OQUEST_, pos);
809 ASTERN(O_QUEST, pos);
810 } else if (EATTWO('\\', '{')) {
813 if (MORE() && isdigit((uch)PEEK())) {
815 (void)REQUIRE(count <= count2, REG_BADBR);
816 } else /* single number with comma */
818 } else /* just a single number */
820 repeat(p, pos, count, count2);
821 if (!EATTWO('\\', '}')) { /* error heuristics */
822 while (MORE() && !SEETWO('\\', '}'))
824 (void)REQUIRE(MORE(), REG_EBRACE);
827 } else if (c == '$') /* $ (but not \$) ends it */
834 - p_count - parse a repetition count
835 == static int p_count(struct parse *p);
837 static int /* the value */
838 p_count(struct parse *p)
843 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
844 count = count*10 + (GETNEXT() - '0');
848 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
853 - p_bracket - parse a bracketed character list
854 == static void p_bracket(struct parse *p);
857 p_bracket(struct parse *p)
862 /* Dept of Truly Sickening Special-Case Kludges */
863 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
868 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
874 if ((cs = allocset(p)) == NULL)
877 if (p->g->cflags®_ICASE)
885 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
889 (void)MUSTEAT(']', REG_EBRACK);
891 if (p->error != 0) /* don't mess things up further */
894 if (cs->invert && p->g->cflags®_NEWLINE)
895 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
897 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
901 EMIT(OANYOF, (int)(cs - p->g->sets));
905 - p_b_term - parse one term of a bracketed character list
906 == static void p_b_term(struct parse *p, cset *cs);
909 p_b_term(struct parse *p, cset *cs)
912 wint_t start, finish;
914 struct xlocale_collate *table =
915 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
917 /* classify what we've got */
918 switch ((MORE()) ? PEEK() : '\0') {
920 c = (MORE2()) ? PEEK2() : '\0';
923 SETERROR(REG_ERANGE);
924 return; /* NOTE RETURN */
931 case ':': /* character class */
933 (void)REQUIRE(MORE(), REG_EBRACK);
935 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
937 (void)REQUIRE(MORE(), REG_EBRACK);
938 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
940 case '=': /* equivalence class */
942 (void)REQUIRE(MORE(), REG_EBRACK);
944 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
946 (void)REQUIRE(MORE(), REG_EBRACK);
947 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
949 default: /* symbol, ordinary character, or range */
950 start = p_b_symbol(p);
951 if (SEE('-') && MORE2() && PEEK2() != ']') {
957 finish = p_b_symbol(p);
963 if (table->__collate_load_error || MB_CUR_MAX > 1) {
964 (void)REQUIRE(start <= finish, REG_ERANGE);
965 CHaddrange(p, cs, start, finish);
967 (void)REQUIRE(__wcollate_range_cmp(start, finish) <= 0, REG_ERANGE);
968 for (i = 0; i <= UCHAR_MAX; i++) {
969 if ( __wcollate_range_cmp(start, i) <= 0
970 && __wcollate_range_cmp(i, finish) <= 0
981 - p_b_cclass - parse a character-class name and deal with it
982 == static void p_b_cclass(struct parse *p, cset *cs);
985 p_b_cclass(struct parse *p, cset *cs)
987 const char *sp = p->next;
992 while (MORE() && isalpha((uch)PEEK()))
995 if (len >= sizeof(clname) - 1) {
996 SETERROR(REG_ECTYPE);
999 memcpy(clname, sp, len);
1001 if ((wct = wctype(clname)) == 0) {
1002 SETERROR(REG_ECTYPE);
1005 CHaddtype(p, cs, wct);
1009 - p_b_eclass - parse an equivalence-class name and deal with it
1010 == static void p_b_eclass(struct parse *p, cset *cs);
1012 * This implementation is incomplete. xxx
1015 p_b_eclass(struct parse *p, cset *cs)
1019 c = p_b_coll_elem(p, '=');
1024 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
1025 == static wint_t p_b_symbol(struct parse *p);
1027 static wint_t /* value of symbol */
1028 p_b_symbol(struct parse *p)
1032 (void)REQUIRE(MORE(), REG_EBRACK);
1033 if (!EATTWO('[', '.'))
1036 /* collating symbol */
1037 value = p_b_coll_elem(p, '.');
1038 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1043 - p_b_coll_elem - parse a collating-element name and look it up
1044 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
1046 static wint_t /* value of collating element */
1047 p_b_coll_elem(struct parse *p,
1048 wint_t endc) /* name ended by endc,']' */
1050 const char *sp = p->next;
1056 while (MORE() && !SEETWO(endc, ']'))
1059 SETERROR(REG_EBRACK);
1063 for (cp = cnames; cp->name != NULL; cp++)
1064 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1065 return(cp->code); /* known name */
1066 memset(&mbs, 0, sizeof(mbs));
1067 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
1068 return (wc); /* single character */
1069 else if (clen == (size_t)-1 || clen == (size_t)-2)
1070 SETERROR(REG_ILLSEQ);
1072 SETERROR(REG_ECOLLATE); /* neither */
1077 - othercase - return the case counterpart of an alphabetic
1078 == static wint_t othercase(wint_t ch);
1080 static wint_t /* if no counterpart, return ch */
1081 othercase(wint_t ch)
1083 assert(iswalpha(ch));
1085 return(towlower(ch));
1086 else if (iswlower(ch))
1087 return(towupper(ch));
1088 else /* peculiar, but could happen */
1093 - bothcases - emit a dualcase version of a two-case character
1094 == static void bothcases(struct parse *p, wint_t ch);
1096 * Boy, is this implementation ever a kludge...
1099 bothcases(struct parse *p, wint_t ch)
1101 const char *oldnext = p->next;
1102 const char *oldend = p->end;
1103 char bracket[3 + MB_LEN_MAX];
1107 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1109 memset(&mbs, 0, sizeof(mbs));
1110 n = wcrtomb(bracket, ch, &mbs);
1111 assert(n != (size_t)-1);
1113 bracket[n + 1] = '\0';
1114 p->end = bracket+n+1;
1116 assert(p->next == p->end);
1122 - ordinary - emit an ordinary character
1123 == static void ordinary(struct parse *p, wint_t ch);
1126 ordinary(struct parse *p, wint_t ch)
1130 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
1132 else if ((ch & OPDMASK) == ch)
1136 * Kludge: character is too big to fit into an OCHAR operand.
1137 * Emit a singleton set.
1139 if ((cs = allocset(p)) == NULL)
1142 EMIT(OANYOF, (int)(cs - p->g->sets));
1147 - nonnewline - emit REG_NEWLINE version of OANY
1148 == static void nonnewline(struct parse *p);
1150 * Boy, is this implementation ever a kludge...
1153 nonnewline(struct parse *p)
1155 const char *oldnext = p->next;
1156 const char *oldend = p->end;
1166 assert(p->next == bracket+3);
1172 - repeat - generate code for a bounded repetition, recursively if needed
1173 == static void repeat(struct parse *p, sopno start, int from, int to);
1176 repeat(struct parse *p,
1177 sopno start, /* operand from here to end of strip */
1178 int from, /* repeated from this number */
1179 int to) /* to this number of times (maybe INFINITY) */
1181 sopno finish = HERE();
1184 # define REP(f, t) ((f)*8 + (t))
1185 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1188 if (p->error != 0) /* head off possible runaway recursion */
1193 switch (REP(MAP(from), MAP(to))) {
1194 case REP(0, 0): /* must be user doing this */
1195 DROP(finish-start); /* drop the operand */
1197 case REP(0, 1): /* as x{1,1}? */
1198 case REP(0, N): /* as x{1,n}? */
1199 case REP(0, INF): /* as x{1,}? */
1200 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1201 INSERT(OCH_, start); /* offset is wrong... */
1202 repeat(p, start+1, 1, to);
1203 ASTERN(OOR1, start);
1204 AHEAD(start); /* ... fix it */
1207 ASTERN(O_CH, THERETHERE());
1209 case REP(1, 1): /* trivial case */
1212 case REP(1, N): /* as x?x{1,n-1} */
1213 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1214 INSERT(OCH_, start);
1215 ASTERN(OOR1, start);
1217 EMIT(OOR2, 0); /* offset very wrong... */
1218 AHEAD(THERE()); /* ...so fix it */
1219 ASTERN(O_CH, THERETHERE());
1220 copy = dupl(p, start+1, finish+1);
1221 assert(copy == finish+4);
1222 repeat(p, copy, 1, to-1);
1224 case REP(1, INF): /* as x+ */
1225 INSERT(OPLUS_, start);
1226 ASTERN(O_PLUS, start);
1228 case REP(N, N): /* as xx{m-1,n-1} */
1229 copy = dupl(p, start, finish);
1230 repeat(p, copy, from-1, to-1);
1232 case REP(N, INF): /* as xx{n-1,INF} */
1233 copy = dupl(p, start, finish);
1234 repeat(p, copy, from-1, to);
1236 default: /* "can't happen" */
1237 SETERROR(REG_ASSERT); /* just in case */
1243 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1244 - character from the parse struct, signals a REG_ILLSEQ error if the
1245 - character can't be converted. Returns the number of bytes consumed.
1248 wgetnext(struct parse *p)
1254 memset(&mbs, 0, sizeof(mbs));
1255 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1256 if (n == (size_t)-1 || n == (size_t)-2) {
1257 SETERROR(REG_ILLSEQ);
1267 - seterr - set an error condition
1268 == static int seterr(struct parse *p, int e);
1270 static int /* useless but makes type checking happy */
1271 seterr(struct parse *p, int e)
1273 if (p->error == 0) /* keep earliest error condition */
1275 p->next = nuls; /* try to bring things to a halt */
1277 return(0); /* make the return value well-defined */
1281 - allocset - allocate a set of characters for []
1282 == static cset *allocset(struct parse *p);
1285 allocset(struct parse *p)
1289 ncs = reallocarray(p->g->sets, p->g->ncsets + 1, sizeof(*ncs));
1291 SETERROR(REG_ESPACE);
1295 cs = &p->g->sets[p->g->ncsets++];
1296 memset(cs, 0, sizeof(*cs));
1302 - freeset - free a now-unused set
1303 == static void freeset(struct parse *p, cset *cs);
1306 freeset(struct parse *p, cset *cs)
1308 cset *top = &p->g->sets[p->g->ncsets];
1313 memset(cs, 0, sizeof(*cs));
1314 if (cs == top-1) /* recover only the easy case */
1319 - singleton - Determine whether a set contains only one character,
1320 - returning it if so, otherwise returning OUT.
1327 for (i = n = 0; i < NC; i++)
1334 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1336 return (cs->wides[0]);
1337 /* Don't bother handling the other cases. */
1342 - CHadd - add character to character set.
1345 CHadd(struct parse *p, cset *cs, wint_t ch)
1347 wint_t nch, *newwides;
1350 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1352 newwides = reallocarray(cs->wides, cs->nwides + 1,
1353 sizeof(*cs->wides));
1354 if (newwides == NULL) {
1355 SETERROR(REG_ESPACE);
1358 cs->wides = newwides;
1359 cs->wides[cs->nwides++] = ch;
1362 if ((nch = towlower(ch)) < NC)
1363 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1364 if ((nch = towupper(ch)) < NC)
1365 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1370 - CHaddrange - add all characters in the range [min,max] to a character set.
1373 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1377 for (; min < NC && min <= max; min++)
1381 newranges = reallocarray(cs->ranges, cs->nranges + 1,
1382 sizeof(*cs->ranges));
1383 if (newranges == NULL) {
1384 SETERROR(REG_ESPACE);
1387 cs->ranges = newranges;
1388 cs->ranges[cs->nranges].min = min;
1389 cs->ranges[cs->nranges].max = max;
1394 - CHaddtype - add all characters of a certain type to a character set.
1397 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1402 for (i = 0; i < NC; i++)
1403 if (iswctype(i, wct))
1405 newtypes = reallocarray(cs->types, cs->ntypes + 1,
1406 sizeof(*cs->types));
1407 if (newtypes == NULL) {
1408 SETERROR(REG_ESPACE);
1411 cs->types = newtypes;
1412 cs->types[cs->ntypes++] = wct;
1416 - dupl - emit a duplicate of a bunch of sops
1417 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1419 static sopno /* start of duplicate */
1420 dupl(struct parse *p,
1421 sopno start, /* from here */
1422 sopno finish) /* to this less one */
1425 sopno len = finish - start;
1427 assert(finish >= start);
1430 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1432 (void) memcpy((char *)(p->strip + p->slen),
1433 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1439 - doemit - emit a strip operator
1440 == static void doemit(struct parse *p, sop op, size_t opnd);
1442 * It might seem better to implement this as a macro with a function as
1443 * hard-case backup, but it's just too big and messy unless there are
1444 * some changes to the data structures. Maybe later.
1447 doemit(struct parse *p, sop op, size_t opnd)
1449 /* avoid making error situations worse */
1453 /* deal with oversize operands ("can't happen", more or less) */
1454 assert(opnd < 1<<OPSHIFT);
1456 /* deal with undersized strip */
1457 if (p->slen >= p->ssize)
1458 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1461 /* finally, it's all reduced to the easy case */
1462 p->strip[p->slen++] = SOP(op, opnd);
1466 - doinsert - insert a sop into the strip
1467 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1470 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1476 /* avoid making error situations worse */
1481 EMIT(op, opnd); /* do checks, ensure space */
1482 assert(HERE() == sn+1);
1485 /* adjust paren pointers */
1487 for (i = 1; i < NPAREN; i++) {
1488 if (p->pbegin[i] >= pos) {
1491 if (p->pend[i] >= pos) {
1496 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1497 (HERE()-pos-1)*sizeof(sop));
1502 - dofwd - complete a forward reference
1503 == static void dofwd(struct parse *p, sopno pos, sop value);
1506 dofwd(struct parse *p, sopno pos, sop value)
1508 /* avoid making error situations worse */
1512 assert(value < 1<<OPSHIFT);
1513 p->strip[pos] = OP(p->strip[pos]) | value;
1517 - enlarge - enlarge the strip
1518 == static int enlarge(struct parse *p, sopno size);
1521 enlarge(struct parse *p, sopno size)
1525 if (p->ssize >= size)
1528 sp = reallocarray(p->strip, size, sizeof(sop));
1530 SETERROR(REG_ESPACE);
1539 - stripsnug - compact the strip
1540 == static void stripsnug(struct parse *p, struct re_guts *g);
1543 stripsnug(struct parse *p, struct re_guts *g)
1545 g->nstates = p->slen;
1546 g->strip = reallocarray((char *)p->strip, p->slen, sizeof(sop));
1547 if (g->strip == NULL) {
1548 SETERROR(REG_ESPACE);
1549 g->strip = p->strip;
1554 - findmust - fill in must and mlen with longest mandatory literal string
1555 == static void findmust(struct parse *p, struct re_guts *g);
1557 * This algorithm could do fancy things like analyzing the operands of |
1558 * for common subsequences. Someday. This code is simple and finds most
1559 * of the interesting cases.
1561 * Note that must and mlen got initialized during setup.
1564 findmust(struct parse *p, struct re_guts *g)
1568 sop *newstart = NULL;
1573 char buf[MB_LEN_MAX];
1577 /* avoid making error situations worse */
1582 * It's not generally safe to do a ``char'' substring search on
1583 * multibyte character strings, but it's safe for at least
1584 * UTF-8 (see RFC 3629).
1586 if (MB_CUR_MAX > 1 &&
1587 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1590 /* find the longest OCHAR sequence in strip */
1594 scan = g->strip + 1;
1598 case OCHAR: /* sequence member */
1599 if (newlen == 0) { /* new sequence */
1600 memset(&mbs, 0, sizeof(mbs));
1601 newstart = scan - 1;
1603 clen = wcrtomb(buf, OPND(s), &mbs);
1604 if (clen == (size_t)-1)
1608 case OPLUS_: /* things that don't break one */
1612 case OQUEST_: /* things that must be skipped */
1614 offset = altoffset(scan, offset);
1619 /* assert() interferes w debug printouts */
1620 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1625 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1627 case OBOW: /* things that break a sequence */
1634 if (newlen > g->mlen) { /* ends one */
1638 g->moffset += offset;
1641 g->moffset = offset;
1649 if (newlen > g->mlen) { /* ends one */
1653 g->moffset += offset;
1656 g->moffset = offset;
1665 case OANYOF: /* may or may not invalidate offset */
1666 /* First, everything as OANY */
1667 if (newlen > g->mlen) { /* ends one */
1671 g->moffset += offset;
1674 g->moffset = offset;
1685 /* Anything here makes it impossible or too hard
1686 * to calculate the offset -- so we give up;
1687 * save the last known good offset, in case the
1688 * must sequence doesn't occur later.
1690 if (newlen > g->mlen) { /* ends one */
1694 g->moffset += offset;
1696 g->moffset = offset;
1702 } while (OP(s) != OEND);
1704 if (g->mlen == 0) { /* there isn't one */
1709 /* turn it into a character string */
1710 g->must = malloc((size_t)g->mlen + 1);
1711 if (g->must == NULL) { /* argh; just forget it */
1718 memset(&mbs, 0, sizeof(mbs));
1719 while (cp < g->must + g->mlen) {
1720 while (OP(s = *scan++) != OCHAR)
1722 clen = wcrtomb(cp, OPND(s), &mbs);
1723 assert(clen != (size_t)-1);
1726 assert(cp == g->must + g->mlen);
1727 *cp++ = '\0'; /* just on general principles */
1731 - altoffset - choose biggest offset among multiple choices
1732 == static int altoffset(sop *scan, int offset);
1734 * Compute, recursively if necessary, the largest offset among multiple
1738 altoffset(sop *scan, int offset)
1744 /* If we gave up already on offsets, return */
1751 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1760 try = altoffset(scan, try);
1767 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1770 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1771 /* We must skip to the next position, or we'll
1772 * leave altoffset() too early.
1798 return largest+offset;
1802 - computejumps - compute char jumps for BM scan
1803 == static void computejumps(struct parse *p, struct re_guts *g);
1805 * This algorithm assumes g->must exists and is has size greater than
1806 * zero. It's based on the algorithm found on Computer Algorithms by
1809 * A char jump is the number of characters one needs to jump based on
1810 * the value of the character from the text that was mismatched.
1813 computejumps(struct parse *p, struct re_guts *g)
1818 /* Avoid making errors worse */
1822 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1823 if (g->charjump == NULL) /* Not a fatal error */
1825 /* Adjust for signed chars, if necessary */
1826 g->charjump = &g->charjump[-(CHAR_MIN)];
1828 /* If the character does not exist in the pattern, the jump
1829 * is equal to the number of characters in the pattern.
1831 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1832 g->charjump[ch] = g->mlen;
1834 /* If the character does exist, compute the jump that would
1835 * take us to the last character in the pattern equal to it
1836 * (notice that we match right to left, so that last character
1837 * is the first one that would be matched).
1839 for (mindex = 0; mindex < g->mlen; mindex++)
1840 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1844 - computematchjumps - compute match jumps for BM scan
1845 == static void computematchjumps(struct parse *p, struct re_guts *g);
1847 * This algorithm assumes g->must exists and is has size greater than
1848 * zero. It's based on the algorithm found on Computer Algorithms by
1851 * A match jump is the number of characters one needs to advance based
1852 * on the already-matched suffix.
1853 * Notice that all values here are minus (g->mlen-1), because of the way
1854 * the search algorithm works.
1857 computematchjumps(struct parse *p, struct re_guts *g)
1859 int mindex; /* General "must" iterator */
1860 int suffix; /* Keeps track of matching suffix */
1861 int ssuffix; /* Keeps track of suffixes' suffix */
1862 int* pmatches; /* pmatches[k] points to the next i
1863 * such that i+1...mlen is a substring
1864 * of k+1...k+mlen-i-1
1867 /* Avoid making errors worse */
1871 pmatches = (int*) malloc(g->mlen * sizeof(int));
1872 if (pmatches == NULL) {
1873 g->matchjump = NULL;
1877 g->matchjump = (int*) malloc(g->mlen * sizeof(int));
1878 if (g->matchjump == NULL) { /* Not a fatal error */
1883 /* Set maximum possible jump for each character in the pattern */
1884 for (mindex = 0; mindex < g->mlen; mindex++)
1885 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1887 /* Compute pmatches[] */
1888 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1889 mindex--, suffix--) {
1890 pmatches[mindex] = suffix;
1892 /* If a mismatch is found, interrupting the substring,
1893 * compute the matchjump for that position. If no
1894 * mismatch is found, then a text substring mismatched
1895 * against the suffix will also mismatch against the
1898 while (suffix < g->mlen
1899 && g->must[mindex] != g->must[suffix]) {
1900 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1901 g->mlen - mindex - 1);
1902 suffix = pmatches[suffix];
1906 /* Compute the matchjump up to the last substring found to jump
1907 * to the beginning of the largest must pattern prefix matching
1910 for (mindex = 0; mindex <= suffix; mindex++)
1911 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1912 g->mlen + suffix - mindex);
1914 ssuffix = pmatches[suffix];
1915 while (suffix < g->mlen) {
1916 while (suffix <= ssuffix && suffix < g->mlen) {
1917 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1918 g->mlen + ssuffix - suffix);
1921 if (suffix < g->mlen)
1922 ssuffix = pmatches[ssuffix];
1929 - pluscount - count + nesting
1930 == static sopno pluscount(struct parse *p, struct re_guts *g);
1932 static sopno /* nesting depth */
1933 pluscount(struct parse *p, struct re_guts *g)
1941 return(0); /* there may not be an OEND */
1943 scan = g->strip + 1;
1951 if (plusnest > maxnest)
1956 } while (OP(s) != OEND);