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>
70 * Branching context, used to keep track of branch state for all of the branch-
71 * aware functions. In addition to keeping track of branch positions for the
72 * p_branch_* functions, we use this to simplify some clumsiness in BREs for
73 * detection of whether ^ is acting as an anchor or being used erroneously and
74 * also for whether we're in a sub-expression or not.
88 * parse structure, passed up and down to avoid global variables and
92 const char *next; /* next character in RE */
93 const char *end; /* end of string (-> NUL normally) */
94 int error; /* has an error been seen? */
95 sop *strip; /* malloced strip */
96 sopno ssize; /* malloced strip size (allocated) */
97 sopno slen; /* malloced strip length (used) */
98 int ncsalloc; /* number of csets allocated */
100 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
101 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
102 sopno pend[NPAREN]; /* -> ) ([0] unused) */
103 bool allowbranch; /* can this expression branch? */
104 bool bre; /* convenience; is this a BRE? */
105 bool (*parse_expr)(struct parse *, struct branchc *);
106 void (*pre_parse)(struct parse *, struct branchc *);
107 void (*post_parse)(struct parse *, struct branchc *);
110 /* ========= begin header generated by ./mkh ========= */
115 /* === regcomp.c === */
116 static bool p_ere_exp(struct parse *p, struct branchc *bc);
117 static void p_str(struct parse *p);
118 static int p_branch_eat_delim(struct parse *p, struct branchc *bc);
119 static void p_branch_ins_offset(struct parse *p, struct branchc *bc);
120 static void p_branch_fix_tail(struct parse *p, struct branchc *bc);
121 static bool p_branch_empty(struct parse *p, struct branchc *bc);
122 static bool p_branch_do(struct parse *p, struct branchc *bc);
123 static void p_bre_pre_parse(struct parse *p, struct branchc *bc);
124 static void p_bre_post_parse(struct parse *p, struct branchc *bc);
125 static void p_re(struct parse *p, int end1, int end2);
126 static bool p_simp_re(struct parse *p, struct branchc *bc);
127 static int p_count(struct parse *p);
128 static void p_bracket(struct parse *p);
129 static int p_range_cmp(wchar_t c1, wchar_t c2);
130 static void p_b_term(struct parse *p, cset *cs);
131 static void p_b_cclass(struct parse *p, cset *cs);
132 static void p_b_eclass(struct parse *p, cset *cs);
133 static wint_t p_b_symbol(struct parse *p);
134 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
135 static wint_t othercase(wint_t ch);
136 static void bothcases(struct parse *p, wint_t ch);
137 static void ordinary(struct parse *p, wint_t ch);
138 static void nonnewline(struct parse *p);
139 static void repeat(struct parse *p, sopno start, int from, int to);
140 static int seterr(struct parse *p, int e);
141 static cset *allocset(struct parse *p);
142 static void freeset(struct parse *p, cset *cs);
143 static void CHadd(struct parse *p, cset *cs, wint_t ch);
144 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
145 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
146 static wint_t singleton(cset *cs);
147 static sopno dupl(struct parse *p, sopno start, sopno finish);
148 static void doemit(struct parse *p, sop op, size_t opnd);
149 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
150 static void dofwd(struct parse *p, sopno pos, sop value);
151 static int enlarge(struct parse *p, sopno size);
152 static void stripsnug(struct parse *p, struct re_guts *g);
153 static void findmust(struct parse *p, struct re_guts *g);
154 static int altoffset(sop *scan, int offset);
155 static void computejumps(struct parse *p, struct re_guts *g);
156 static void computematchjumps(struct parse *p, struct re_guts *g);
157 static sopno pluscount(struct parse *p, struct re_guts *g);
158 static wint_t wgetnext(struct parse *p);
163 /* ========= end header generated by ./mkh ========= */
165 static char nuls[10]; /* place to point scanner in event of error */
168 * macros for use with parse structure
169 * BEWARE: these know that the parse structure is named `p' !!!
171 #define PEEK() (*p->next)
172 #define PEEK2() (*(p->next+1))
173 #define MORE() (p->next < p->end)
174 #define MORE2() (p->next+1 < p->end)
175 #define SEE(c) (MORE() && PEEK() == (c))
176 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
177 #define SEESPEC(a) (p->bre ? SEETWO('\\', a) : SEE(a))
178 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
179 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
180 #define NEXT() (p->next++)
181 #define NEXT2() (p->next += 2)
182 #define NEXTn(n) (p->next += (n))
183 #define GETNEXT() (*p->next++)
184 #define WGETNEXT() wgetnext(p)
185 #define SETERROR(e) seterr(p, (e))
186 #define REQUIRE(co, e) ((co) || SETERROR(e))
187 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
188 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
189 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
190 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
191 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
192 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
193 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
194 #define HERE() (p->slen)
195 #define THERE() (p->slen - 1)
196 #define THERETHERE() (p->slen - 2)
197 #define DROP(n) (p->slen -= (n))
199 /* Macro used by computejump()/computematchjump() */
200 #define MIN(a,b) ((a)<(b)?(a):(b))
203 - regcomp - interface for parser and compilation
204 = extern int regcomp(regex_t *, const char *, int);
205 = #define REG_BASIC 0000
206 = #define REG_EXTENDED 0001
207 = #define REG_ICASE 0002
208 = #define REG_NOSUB 0004
209 = #define REG_NEWLINE 0010
210 = #define REG_NOSPEC 0020
211 = #define REG_PEND 0040
212 = #define REG_DUMP 0200
214 int /* 0 success, otherwise REG_something */
215 regcomp(regex_t * __restrict preg,
216 const char * __restrict pattern,
221 struct parse *p = &pa;
226 # define GOODFLAGS(f) (f)
228 # define GOODFLAGS(f) ((f)&~REG_DUMP)
231 cflags = GOODFLAGS(cflags);
232 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
235 if (cflags®_PEND) {
236 if (preg->re_endp < pattern)
238 len = preg->re_endp - pattern;
240 len = strlen(pattern);
242 /* do the mallocs early so failure handling is easy */
243 g = (struct re_guts *)malloc(sizeof(struct re_guts));
247 * Limit the pattern space to avoid a 32-bit overflow on buffer
248 * extension. Also avoid any signed overflow in case of conversion
249 * so make the real limit based on a 31-bit overflow.
251 * Likely not applicable on 64-bit systems but handle the case
252 * generically (who are we to stop people from using ~715MB+
255 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
260 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
261 assert(p->ssize >= len);
263 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
265 if (p->strip == NULL) {
272 p->next = pattern; /* convenience; we do not modify it */
273 p->end = p->next + len;
276 for (i = 0; i < NPAREN; i++) {
280 if (cflags & REG_EXTENDED) {
281 p->allowbranch = true;
283 p->parse_expr = p_ere_exp;
285 p->post_parse = NULL;
287 p->allowbranch = false;
289 p->parse_expr = p_simp_re;
290 p->pre_parse = p_bre_pre_parse;
291 p->post_parse = p_bre_post_parse;
309 g->firststate = THERE();
310 if (cflags & REG_NOSPEC)
315 g->laststate = THERE();
317 /* tidy up loose ends and fill things in */
320 /* only use Boyer-Moore algorithm if the pattern is bigger
321 * than three characters
325 computematchjumps(p, g);
326 if(g->matchjump == NULL && g->charjump != NULL) {
331 g->nplus = pluscount(p, g);
333 preg->re_nsub = g->nsub;
335 preg->re_magic = MAGIC1;
337 /* not debugging, so can't rely on the assert() in regexec() */
339 SETERROR(REG_ASSERT);
342 /* win or lose, we're done */
343 if (p->error != 0) /* lose */
349 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op,
350 - return whether we should terminate or not
351 == static bool p_ere_exp(struct parse *p);
354 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)
543 * Insert necessary branch book-keeping operations. This emits a
544 * bogus 'next' offset, since we still have more to parse
547 p_branch_ins_offset(struct parse *p, struct branchc *bc)
550 if (bc->nbranch == 0) {
551 INSERT(OCH_, bc->start); /* offset is wrong */
553 bc->back = bc->start;
556 ASTERN(OOR1, bc->back);
558 AHEAD(bc->fwd); /* fix previous offset */
560 EMIT(OOR2, 0); /* offset is very wrong */
565 * Fix the offset of the tail branch, if we actually had any branches.
566 * This is to correct the bogus placeholder offset that we use.
569 p_branch_fix_tail(struct parse *p, struct branchc *bc)
572 /* Fix bogus offset at the tail if we actually have branches */
573 if (bc->nbranch > 0) {
575 ASTERN(O_CH, bc->back);
580 * Signal to the parser that an empty branch has been encountered; this will,
581 * in the future, be used to allow for more permissive behavior with empty
582 * branches. The return value should indicate whether parsing may continue
586 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_range_cmp(wchar_t c1, wchar_t c2)
908 return __wcollate_range_cmp(c1, c2);
910 /* Copied from libc/collate __wcollate_range_cmp */
911 wchar_t s1[2], s2[2];
917 return (wcscoll(s1, s2));
922 - p_b_term - parse one term of a bracketed character list
923 == static void p_b_term(struct parse *p, cset *cs);
926 p_b_term(struct parse *p, cset *cs)
929 wint_t start, finish;
932 struct xlocale_collate *table =
933 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
935 /* classify what we've got */
936 switch ((MORE()) ? PEEK() : '\0') {
938 c = (MORE2()) ? PEEK2() : '\0';
941 SETERROR(REG_ERANGE);
942 return; /* NOTE RETURN */
949 case ':': /* character class */
951 (void)REQUIRE(MORE(), REG_EBRACK);
953 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
955 (void)REQUIRE(MORE(), REG_EBRACK);
956 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
958 case '=': /* equivalence class */
960 (void)REQUIRE(MORE(), REG_EBRACK);
962 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
964 (void)REQUIRE(MORE(), REG_EBRACK);
965 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
967 default: /* symbol, ordinary character, or range */
968 start = p_b_symbol(p);
969 if (SEE('-') && MORE2() && PEEK2() != ']') {
975 finish = p_b_symbol(p);
982 if (table->__collate_load_error || MB_CUR_MAX > 1) {
984 if (MB_CUR_MAX > 1) {
986 (void)REQUIRE(start <= finish, REG_ERANGE);
987 CHaddrange(p, cs, start, finish);
989 (void)REQUIRE(p_range_cmp(start, finish) <= 0, REG_ERANGE);
990 for (i = 0; i <= UCHAR_MAX; i++) {
991 if (p_range_cmp(start, i) <= 0 &&
992 p_range_cmp(i, finish) <= 0 )
1002 - p_b_cclass - parse a character-class name and deal with it
1003 == static void p_b_cclass(struct parse *p, cset *cs);
1006 p_b_cclass(struct parse *p, cset *cs)
1008 const char *sp = p->next;
1013 while (MORE() && isalpha((uch)PEEK()))
1016 if (len >= sizeof(clname) - 1) {
1017 SETERROR(REG_ECTYPE);
1020 memcpy(clname, sp, len);
1022 if ((wct = wctype(clname)) == 0) {
1023 SETERROR(REG_ECTYPE);
1026 CHaddtype(p, cs, wct);
1030 - p_b_eclass - parse an equivalence-class name and deal with it
1031 == static void p_b_eclass(struct parse *p, cset *cs);
1033 * This implementation is incomplete. xxx
1036 p_b_eclass(struct parse *p, cset *cs)
1040 c = p_b_coll_elem(p, '=');
1045 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
1046 == static wint_t p_b_symbol(struct parse *p);
1048 static wint_t /* value of symbol */
1049 p_b_symbol(struct parse *p)
1053 (void)REQUIRE(MORE(), REG_EBRACK);
1054 if (!EATTWO('[', '.'))
1057 /* collating symbol */
1058 value = p_b_coll_elem(p, '.');
1059 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1064 - p_b_coll_elem - parse a collating-element name and look it up
1065 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
1067 static wint_t /* value of collating element */
1068 p_b_coll_elem(struct parse *p,
1069 wint_t endc) /* name ended by endc,']' */
1071 const char *sp = p->next;
1077 while (MORE() && !SEETWO(endc, ']'))
1080 SETERROR(REG_EBRACK);
1084 for (cp = cnames; cp->name != NULL; cp++)
1085 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1086 return(cp->code); /* known name */
1087 memset(&mbs, 0, sizeof(mbs));
1088 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
1089 return (wc); /* single character */
1090 else if (clen == (size_t)-1 || clen == (size_t)-2)
1091 SETERROR(REG_ILLSEQ);
1093 SETERROR(REG_ECOLLATE); /* neither */
1098 - othercase - return the case counterpart of an alphabetic
1099 == static wint_t othercase(wint_t ch);
1101 static wint_t /* if no counterpart, return ch */
1102 othercase(wint_t ch)
1104 assert(iswalpha(ch));
1106 return(towlower(ch));
1107 else if (iswlower(ch))
1108 return(towupper(ch));
1109 else /* peculiar, but could happen */
1114 - bothcases - emit a dualcase version of a two-case character
1115 == static void bothcases(struct parse *p, wint_t ch);
1117 * Boy, is this implementation ever a kludge...
1120 bothcases(struct parse *p, wint_t ch)
1122 const char *oldnext = p->next;
1123 const char *oldend = p->end;
1124 char bracket[3 + MB_LEN_MAX];
1128 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1130 memset(&mbs, 0, sizeof(mbs));
1131 n = wcrtomb(bracket, ch, &mbs);
1132 assert(n != (size_t)-1);
1134 bracket[n + 1] = '\0';
1135 p->end = bracket+n+1;
1137 assert(p->next == p->end);
1143 - ordinary - emit an ordinary character
1144 == static void ordinary(struct parse *p, wint_t ch);
1147 ordinary(struct parse *p, wint_t ch)
1151 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
1153 else if ((ch & OPDMASK) == ch)
1157 * Kludge: character is too big to fit into an OCHAR operand.
1158 * Emit a singleton set.
1160 if ((cs = allocset(p)) == NULL)
1163 EMIT(OANYOF, (int)(cs - p->g->sets));
1168 - nonnewline - emit REG_NEWLINE version of OANY
1169 == static void nonnewline(struct parse *p);
1171 * Boy, is this implementation ever a kludge...
1174 nonnewline(struct parse *p)
1176 const char *oldnext = p->next;
1177 const char *oldend = p->end;
1187 assert(p->next == bracket+3);
1193 - repeat - generate code for a bounded repetition, recursively if needed
1194 == static void repeat(struct parse *p, sopno start, int from, int to);
1197 repeat(struct parse *p,
1198 sopno start, /* operand from here to end of strip */
1199 int from, /* repeated from this number */
1200 int to) /* to this number of times (maybe INFINITY) */
1202 sopno finish = HERE();
1205 # define REP(f, t) ((f)*8 + (t))
1206 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1209 if (p->error != 0) /* head off possible runaway recursion */
1214 switch (REP(MAP(from), MAP(to))) {
1215 case REP(0, 0): /* must be user doing this */
1216 DROP(finish-start); /* drop the operand */
1218 case REP(0, 1): /* as x{1,1}? */
1219 case REP(0, N): /* as x{1,n}? */
1220 case REP(0, INF): /* as x{1,}? */
1221 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1222 INSERT(OCH_, start); /* offset is wrong... */
1223 repeat(p, start+1, 1, to);
1224 ASTERN(OOR1, start);
1225 AHEAD(start); /* ... fix it */
1228 ASTERN(O_CH, THERETHERE());
1230 case REP(1, 1): /* trivial case */
1233 case REP(1, N): /* as x?x{1,n-1} */
1234 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1235 INSERT(OCH_, start);
1236 ASTERN(OOR1, start);
1238 EMIT(OOR2, 0); /* offset very wrong... */
1239 AHEAD(THERE()); /* ...so fix it */
1240 ASTERN(O_CH, THERETHERE());
1241 copy = dupl(p, start+1, finish+1);
1242 assert(copy == finish+4);
1243 repeat(p, copy, 1, to-1);
1245 case REP(1, INF): /* as x+ */
1246 INSERT(OPLUS_, start);
1247 ASTERN(O_PLUS, start);
1249 case REP(N, N): /* as xx{m-1,n-1} */
1250 copy = dupl(p, start, finish);
1251 repeat(p, copy, from-1, to-1);
1253 case REP(N, INF): /* as xx{n-1,INF} */
1254 copy = dupl(p, start, finish);
1255 repeat(p, copy, from-1, to);
1257 default: /* "can't happen" */
1258 SETERROR(REG_ASSERT); /* just in case */
1264 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1265 - character from the parse struct, signals a REG_ILLSEQ error if the
1266 - character can't be converted. Returns the number of bytes consumed.
1269 wgetnext(struct parse *p)
1275 memset(&mbs, 0, sizeof(mbs));
1276 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1277 if (n == (size_t)-1 || n == (size_t)-2) {
1278 SETERROR(REG_ILLSEQ);
1288 - seterr - set an error condition
1289 == static int seterr(struct parse *p, int e);
1291 static int /* useless but makes type checking happy */
1292 seterr(struct parse *p, int e)
1294 if (p->error == 0) /* keep earliest error condition */
1296 p->next = nuls; /* try to bring things to a halt */
1298 return(0); /* make the return value well-defined */
1302 - allocset - allocate a set of characters for []
1303 == static cset *allocset(struct parse *p);
1306 allocset(struct parse *p)
1310 ncs = reallocarray(p->g->sets, p->g->ncsets + 1, sizeof(*ncs));
1312 SETERROR(REG_ESPACE);
1316 cs = &p->g->sets[p->g->ncsets++];
1317 memset(cs, 0, sizeof(*cs));
1323 - freeset - free a now-unused set
1324 == static void freeset(struct parse *p, cset *cs);
1327 freeset(struct parse *p, cset *cs)
1329 cset *top = &p->g->sets[p->g->ncsets];
1334 memset(cs, 0, sizeof(*cs));
1335 if (cs == top-1) /* recover only the easy case */
1340 - singleton - Determine whether a set contains only one character,
1341 - returning it if so, otherwise returning OUT.
1348 for (i = n = 0; i < NC; i++)
1355 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1357 return (cs->wides[0]);
1358 /* Don't bother handling the other cases. */
1363 - CHadd - add character to character set.
1366 CHadd(struct parse *p, cset *cs, wint_t ch)
1368 wint_t nch, *newwides;
1371 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1373 newwides = reallocarray(cs->wides, cs->nwides + 1,
1374 sizeof(*cs->wides));
1375 if (newwides == NULL) {
1376 SETERROR(REG_ESPACE);
1379 cs->wides = newwides;
1380 cs->wides[cs->nwides++] = ch;
1383 if ((nch = towlower(ch)) < NC)
1384 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1385 if ((nch = towupper(ch)) < NC)
1386 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1391 - CHaddrange - add all characters in the range [min,max] to a character set.
1394 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1398 for (; min < NC && min <= max; min++)
1402 newranges = reallocarray(cs->ranges, cs->nranges + 1,
1403 sizeof(*cs->ranges));
1404 if (newranges == NULL) {
1405 SETERROR(REG_ESPACE);
1408 cs->ranges = newranges;
1409 cs->ranges[cs->nranges].min = min;
1410 cs->ranges[cs->nranges].max = max;
1415 - CHaddtype - add all characters of a certain type to a character set.
1418 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1423 for (i = 0; i < NC; i++)
1424 if (iswctype(i, wct))
1426 newtypes = reallocarray(cs->types, cs->ntypes + 1,
1427 sizeof(*cs->types));
1428 if (newtypes == NULL) {
1429 SETERROR(REG_ESPACE);
1432 cs->types = newtypes;
1433 cs->types[cs->ntypes++] = wct;
1437 - dupl - emit a duplicate of a bunch of sops
1438 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1440 static sopno /* start of duplicate */
1441 dupl(struct parse *p,
1442 sopno start, /* from here */
1443 sopno finish) /* to this less one */
1446 sopno len = finish - start;
1448 assert(finish >= start);
1451 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1453 (void) memcpy((char *)(p->strip + p->slen),
1454 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1460 - doemit - emit a strip operator
1461 == static void doemit(struct parse *p, sop op, size_t opnd);
1463 * It might seem better to implement this as a macro with a function as
1464 * hard-case backup, but it's just too big and messy unless there are
1465 * some changes to the data structures. Maybe later.
1468 doemit(struct parse *p, sop op, size_t opnd)
1470 /* avoid making error situations worse */
1474 /* deal with oversize operands ("can't happen", more or less) */
1475 assert(opnd < 1<<OPSHIFT);
1477 /* deal with undersized strip */
1478 if (p->slen >= p->ssize)
1479 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1482 /* finally, it's all reduced to the easy case */
1483 p->strip[p->slen++] = SOP(op, opnd);
1487 - doinsert - insert a sop into the strip
1488 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1491 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1497 /* avoid making error situations worse */
1502 EMIT(op, opnd); /* do checks, ensure space */
1503 assert(HERE() == sn+1);
1506 /* adjust paren pointers */
1508 for (i = 1; i < NPAREN; i++) {
1509 if (p->pbegin[i] >= pos) {
1512 if (p->pend[i] >= pos) {
1517 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1518 (HERE()-pos-1)*sizeof(sop));
1523 - dofwd - complete a forward reference
1524 == static void dofwd(struct parse *p, sopno pos, sop value);
1527 dofwd(struct parse *p, sopno pos, sop value)
1529 /* avoid making error situations worse */
1533 assert(value < 1<<OPSHIFT);
1534 p->strip[pos] = OP(p->strip[pos]) | value;
1538 - enlarge - enlarge the strip
1539 == static int enlarge(struct parse *p, sopno size);
1542 enlarge(struct parse *p, sopno size)
1546 if (p->ssize >= size)
1549 sp = reallocarray(p->strip, size, sizeof(sop));
1551 SETERROR(REG_ESPACE);
1560 - stripsnug - compact the strip
1561 == static void stripsnug(struct parse *p, struct re_guts *g);
1564 stripsnug(struct parse *p, struct re_guts *g)
1566 g->nstates = p->slen;
1567 g->strip = reallocarray((char *)p->strip, p->slen, sizeof(sop));
1568 if (g->strip == NULL) {
1569 SETERROR(REG_ESPACE);
1570 g->strip = p->strip;
1575 - findmust - fill in must and mlen with longest mandatory literal string
1576 == static void findmust(struct parse *p, struct re_guts *g);
1578 * This algorithm could do fancy things like analyzing the operands of |
1579 * for common subsequences. Someday. This code is simple and finds most
1580 * of the interesting cases.
1582 * Note that must and mlen got initialized during setup.
1585 findmust(struct parse *p, struct re_guts *g)
1589 sop *newstart = NULL;
1594 char buf[MB_LEN_MAX];
1598 /* avoid making error situations worse */
1603 * It's not generally safe to do a ``char'' substring search on
1604 * multibyte character strings, but it's safe for at least
1605 * UTF-8 (see RFC 3629).
1607 if (MB_CUR_MAX > 1 &&
1608 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1611 /* find the longest OCHAR sequence in strip */
1615 scan = g->strip + 1;
1619 case OCHAR: /* sequence member */
1620 if (newlen == 0) { /* new sequence */
1621 memset(&mbs, 0, sizeof(mbs));
1622 newstart = scan - 1;
1624 clen = wcrtomb(buf, OPND(s), &mbs);
1625 if (clen == (size_t)-1)
1629 case OPLUS_: /* things that don't break one */
1633 case OQUEST_: /* things that must be skipped */
1635 offset = altoffset(scan, offset);
1640 /* assert() interferes w debug printouts */
1641 if (OP(s) != (sop)O_QUEST &&
1642 OP(s) != (sop)O_CH && OP(s) != (sop)OOR2) {
1646 } while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH);
1648 case OBOW: /* things that break a sequence */
1655 if (newlen > (sopno)g->mlen) { /* ends one */
1659 g->moffset += offset;
1662 g->moffset = offset;
1670 if (newlen > (sopno)g->mlen) { /* ends one */
1674 g->moffset += offset;
1677 g->moffset = offset;
1686 case OANYOF: /* may or may not invalidate offset */
1687 /* First, everything as OANY */
1688 if (newlen > (sopno)g->mlen) { /* ends one */
1692 g->moffset += offset;
1695 g->moffset = offset;
1706 /* Anything here makes it impossible or too hard
1707 * to calculate the offset -- so we give up;
1708 * save the last known good offset, in case the
1709 * must sequence doesn't occur later.
1711 if (newlen > (sopno)g->mlen) { /* ends one */
1715 g->moffset += offset;
1717 g->moffset = offset;
1723 } while (OP(s) != OEND);
1725 if (g->mlen == 0) { /* there isn't one */
1730 /* turn it into a character string */
1731 g->must = malloc((size_t)g->mlen + 1);
1732 if (g->must == NULL) { /* argh; just forget it */
1739 memset(&mbs, 0, sizeof(mbs));
1740 while (cp < g->must + g->mlen) {
1741 while (OP(s = *scan++) != OCHAR)
1743 clen = wcrtomb(cp, OPND(s), &mbs);
1744 assert(clen != (size_t)-1);
1747 assert(cp == g->must + g->mlen);
1748 *cp++ = '\0'; /* just on general principles */
1752 - altoffset - choose biggest offset among multiple choices
1753 == static int altoffset(sop *scan, int offset);
1755 * Compute, recursively if necessary, the largest offset among multiple
1759 altoffset(sop *scan, int offset)
1765 /* If we gave up already on offsets, return */
1772 while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH) {
1781 try = altoffset(scan, try);
1788 if (OP(s) != (sop)O_QUEST &&
1789 OP(s) != (sop)O_CH && OP(s) != (sop)OOR2)
1791 } while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH);
1792 /* We must skip to the next position, or we'll
1793 * leave altoffset() too early.
1819 return largest+offset;
1823 - computejumps - compute char jumps for BM scan
1824 == static void computejumps(struct parse *p, struct re_guts *g);
1826 * This algorithm assumes g->must exists and is has size greater than
1827 * zero. It's based on the algorithm found on Computer Algorithms by
1830 * A char jump is the number of characters one needs to jump based on
1831 * the value of the character from the text that was mismatched.
1834 computejumps(struct parse *p, struct re_guts *g)
1839 /* Avoid making errors worse */
1843 g->charjump = (int *)malloc((NC_MAX + 1) * sizeof(int));
1844 if (g->charjump == NULL) /* Not a fatal error */
1846 /* Adjust for signed chars, if necessary */
1847 g->charjump = &g->charjump[-(CHAR_MIN)];
1849 /* If the character does not exist in the pattern, the jump
1850 * is equal to the number of characters in the pattern.
1852 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1853 g->charjump[ch] = g->mlen;
1855 /* If the character does exist, compute the jump that would
1856 * take us to the last character in the pattern equal to it
1857 * (notice that we match right to left, so that last character
1858 * is the first one that would be matched).
1860 for (mindex = 0; mindex < g->mlen; mindex++)
1861 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1865 - computematchjumps - compute match jumps for BM scan
1866 == static void computematchjumps(struct parse *p, struct re_guts *g);
1868 * This algorithm assumes g->must exists and is has size greater than
1869 * zero. It's based on the algorithm found on Computer Algorithms by
1872 * A match jump is the number of characters one needs to advance based
1873 * on the already-matched suffix.
1874 * Notice that all values here are minus (g->mlen-1), because of the way
1875 * the search algorithm works.
1878 computematchjumps(struct parse *p, struct re_guts *g)
1880 int mindex; /* General "must" iterator */
1881 int suffix; /* Keeps track of matching suffix */
1882 int ssuffix; /* Keeps track of suffixes' suffix */
1883 int* pmatches; /* pmatches[k] points to the next i
1884 * such that i+1...mlen is a substring
1885 * of k+1...k+mlen-i-1
1888 /* Avoid making errors worse */
1892 pmatches = (int*) malloc(g->mlen * sizeof(int));
1893 if (pmatches == NULL) {
1894 g->matchjump = NULL;
1898 g->matchjump = (int*) malloc(g->mlen * sizeof(int));
1899 if (g->matchjump == NULL) { /* Not a fatal error */
1904 /* Set maximum possible jump for each character in the pattern */
1905 for (mindex = 0; mindex < g->mlen; mindex++)
1906 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1908 /* Compute pmatches[] */
1909 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1910 mindex--, suffix--) {
1911 pmatches[mindex] = suffix;
1913 /* If a mismatch is found, interrupting the substring,
1914 * compute the matchjump for that position. If no
1915 * mismatch is found, then a text substring mismatched
1916 * against the suffix will also mismatch against the
1919 while (suffix < g->mlen
1920 && g->must[mindex] != g->must[suffix]) {
1921 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1922 g->mlen - mindex - 1);
1923 suffix = pmatches[suffix];
1927 /* Compute the matchjump up to the last substring found to jump
1928 * to the beginning of the largest must pattern prefix matching
1931 for (mindex = 0; mindex <= suffix; mindex++)
1932 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1933 g->mlen + suffix - mindex);
1935 ssuffix = pmatches[suffix];
1936 while (suffix < g->mlen) {
1937 while (suffix <= ssuffix && suffix < g->mlen) {
1938 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1939 g->mlen + ssuffix - suffix);
1942 if (suffix < g->mlen)
1943 ssuffix = pmatches[ssuffix];
1950 - pluscount - count + nesting
1951 == static sopno pluscount(struct parse *p, struct re_guts *g);
1953 static sopno /* nesting depth */
1954 pluscount(struct parse *p, struct re_guts *g)
1962 return(0); /* there may not be an OEND */
1964 scan = g->strip + 1;
1972 if (plusnest > maxnest)
1977 } while (OP(s) != OEND);