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))
200 static int never = 0; /* for use in asserts; shuts lint up */
202 #define never 0 /* some <assert.h>s have bugs too */
205 /* Macro used by computejump()/computematchjump() */
206 #define MIN(a,b) ((a)<(b)?(a):(b))
209 - regcomp - interface for parser and compilation
210 = extern int regcomp(regex_t *, const char *, int);
211 = #define REG_BASIC 0000
212 = #define REG_EXTENDED 0001
213 = #define REG_ICASE 0002
214 = #define REG_NOSUB 0004
215 = #define REG_NEWLINE 0010
216 = #define REG_NOSPEC 0020
217 = #define REG_PEND 0040
218 = #define REG_DUMP 0200
220 int /* 0 success, otherwise REG_something */
221 regcomp(regex_t * __restrict preg,
222 const char * __restrict pattern,
227 struct parse *p = &pa;
232 # define GOODFLAGS(f) (f)
234 # define GOODFLAGS(f) ((f)&~REG_DUMP)
237 cflags = GOODFLAGS(cflags);
238 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
241 if (cflags®_PEND) {
242 if (preg->re_endp < pattern)
244 len = preg->re_endp - pattern;
246 len = strlen(pattern);
248 /* do the mallocs early so failure handling is easy */
249 g = (struct re_guts *)malloc(sizeof(struct re_guts));
253 * Limit the pattern space to avoid a 32-bit overflow on buffer
254 * extension. Also avoid any signed overflow in case of conversion
255 * so make the real limit based on a 31-bit overflow.
257 * Likely not applicable on 64-bit systems but handle the case
258 * generically (who are we to stop people from using ~715MB+
261 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
266 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
267 assert(p->ssize >= len);
269 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
271 if (p->strip == NULL) {
278 p->next = pattern; /* convenience; we do not modify it */
279 p->end = p->next + len;
282 for (i = 0; i < NPAREN; i++) {
286 if (cflags & REG_EXTENDED) {
287 p->allowbranch = true;
289 p->parse_expr = p_ere_exp;
291 p->post_parse = NULL;
293 p->allowbranch = false;
295 p->parse_expr = p_simp_re;
296 p->pre_parse = p_bre_pre_parse;
297 p->post_parse = p_bre_post_parse;
315 g->firststate = THERE();
316 if (cflags & REG_NOSPEC)
321 g->laststate = THERE();
323 /* tidy up loose ends and fill things in */
326 /* only use Boyer-Moore algorithm if the pattern is bigger
327 * than three characters
331 computematchjumps(p, g);
332 if(g->matchjump == NULL && g->charjump != NULL) {
337 g->nplus = pluscount(p, g);
339 preg->re_nsub = g->nsub;
341 preg->re_magic = MAGIC1;
343 /* not debugging, so can't rely on the assert() in regexec() */
345 SETERROR(REG_ASSERT);
348 /* win or lose, we're done */
349 if (p->error != 0) /* lose */
355 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op,
356 - return whether we should terminate or not
357 == static bool p_ere_exp(struct parse *p);
360 p_ere_exp(struct parse *p, struct branchc *bc)
371 assert(MORE()); /* caller should have ensured this */
377 (void)REQUIRE(MORE(), REG_EPAREN);
381 p->pbegin[subno] = HERE();
382 EMIT(OLPAREN, subno);
385 if (subno < NPAREN) {
386 p->pend[subno] = HERE();
387 assert(p->pend[subno] != 0);
389 EMIT(ORPAREN, subno);
390 (void)MUSTEAT(')', REG_EPAREN);
392 #ifndef POSIX_MISTAKE
393 case ')': /* happens only if no current unmatched ( */
395 * You may ask, why the ifndef? Because I didn't notice
396 * this until slightly too late for 1003.2, and none of the
397 * other 1003.2 regular-expression reviewers noticed it at
398 * all. So an unmatched ) is legal POSIX, at least until
399 * we can get it fixed.
401 SETERROR(REG_EPAREN);
406 p->g->iflags |= USEBOL;
412 p->g->iflags |= USEEOL;
422 SETERROR(REG_BADRPT);
425 if (p->g->cflags®_NEWLINE)
434 (void)REQUIRE(MORE(), REG_EESCAPE);
460 /* we call { a repetition if followed by a digit */
461 if (!( c == '*' || c == '+' || c == '?' || c == '{'))
462 return (false); /* no repetition, we're done */
464 (void)REQUIRE(MORE2() && \
465 (isdigit((uch)PEEK2()) || PEEK2() == ','), REG_BADRPT);
468 (void)REQUIRE(!wascaret, REG_BADRPT);
470 case '*': /* implemented as +? */
471 /* this case does not require the (y|) trick, noKLUDGE */
474 INSERT(OQUEST_, pos);
475 ASTERN(O_QUEST, pos);
482 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
483 INSERT(OCH_, pos); /* offset slightly wrong */
484 ASTERN(OOR1, pos); /* this one's right */
485 AHEAD(pos); /* fix the OCH_ */
486 EMIT(OOR2, 0); /* offset very wrong... */
487 AHEAD(THERE()); /* ...so fix it */
488 ASTERN(O_CH, THERETHERE());
493 if (isdigit((uch)PEEK())) {
495 (void)REQUIRE(count <= count2, REG_BADBR);
496 } else /* single number with comma */
498 } else /* just a single number */
500 repeat(p, pos, count, count2);
501 if (!EAT('}')) { /* error heuristics */
502 while (MORE() && PEEK() != '}')
504 (void)REQUIRE(MORE(), REG_EBRACE);
513 if (!( c == '*' || c == '+' || c == '?' ||
514 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
516 SETERROR(REG_BADRPT);
521 - p_str - string (no metacharacters) "parser"
522 == static void p_str(struct parse *p);
525 p_str(struct parse *p)
527 (void)REQUIRE(MORE(), REG_EMPTY);
529 ordinary(p, WGETNEXT());
533 * Eat consecutive branch delimiters for the kind of expression that we are
534 * parsing, return the number of delimiters that we ate.
537 p_branch_eat_delim(struct parse *p, struct branchc *bc)
549 * Insert necessary branch book-keeping operations. This emits a
550 * bogus 'next' offset, since we still have more to parse
553 p_branch_ins_offset(struct parse *p, struct branchc *bc)
556 if (bc->nbranch == 0) {
557 INSERT(OCH_, bc->start); /* offset is wrong */
559 bc->back = bc->start;
562 ASTERN(OOR1, bc->back);
564 AHEAD(bc->fwd); /* fix previous offset */
566 EMIT(OOR2, 0); /* offset is very wrong */
571 * Fix the offset of the tail branch, if we actually had any branches.
572 * This is to correct the bogus placeholder offset that we use.
575 p_branch_fix_tail(struct parse *p, struct branchc *bc)
578 /* Fix bogus offset at the tail if we actually have branches */
579 if (bc->nbranch > 0) {
581 ASTERN(O_CH, bc->back);
586 * Signal to the parser that an empty branch has been encountered; this will,
587 * in the future, be used to allow for more permissive behavior with empty
588 * branches. The return value should indicate whether parsing may continue
592 p_branch_empty(struct parse *p, struct branchc *bc)
601 * Take care of any branching requirements. This includes inserting the
602 * appropriate branching instructions as well as eating all of the branch
603 * delimiters until we either run out of pattern or need to parse more pattern.
606 p_branch_do(struct parse *p, struct branchc *bc)
610 ate = p_branch_eat_delim(p, bc);
613 else if ((ate > 1 || (bc->outer && !MORE())) && !p_branch_empty(p, bc))
615 * Halt parsing only if we have an empty branch and p_branch_empty
616 * indicates that we must not continue. In the future, this will not
617 * necessarily be an error.
620 p_branch_ins_offset(p, bc);
626 p_bre_pre_parse(struct parse *p, struct branchc *bc)
631 * Does not move cleanly into expression parser because of
632 * ordinary interpration of * at the beginning position of
637 p->g->iflags |= USEBOL;
643 p_bre_post_parse(struct parse *p, struct branchc *bc)
646 /* Expression is terminating due to EOL token */
650 p->g->iflags |= USEEOL;
656 - p_re - Top level parser, concatenation and BRE anchoring
657 == static void p_re(struct parse *p, int end1, int end2);
658 * Giving end1 as OUT essentially eliminates the end1/end2 check.
660 * This implementation is a bit of a kludge, in that a trailing $ is first
661 * taken as an ordinary character and then revised to be an anchor.
662 * The amount of lookahead needed to avoid this kludge is excessive.
665 p_re(struct parse *p,
666 int end1, /* first terminating character */
667 int end2) /* second terminating character; ignored for EREs */
672 if (end1 == OUT && end2 == OUT)
676 #define SEEEND() (!p->bre ? SEE(end1) : SEETWO(end1, end2))
680 bc.terminate = false;
681 if (p->pre_parse != NULL)
682 p->pre_parse(p, &bc);
683 while (MORE() && (!p->allowbranch || !SEESPEC('|')) && !SEEEND()) {
684 bc.terminate = p->parse_expr(p, &bc);
687 if (p->post_parse != NULL)
688 p->post_parse(p, &bc);
689 (void) REQUIRE(HERE() != bc.start, REG_EMPTY);
693 * p_branch_do's return value indicates whether we should
694 * continue parsing or not. This is both for correctness and
695 * a slight optimization, because it will check if we've
696 * encountered an empty branch or the end of the string
697 * immediately following a branch delimiter.
699 if (!p_branch_do(p, &bc))
704 p_branch_fix_tail(p, &bc);
705 assert(!MORE() || SEE(end1));
709 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
710 == static bool p_simp_re(struct parse *p, struct branchc *bc);
712 static bool /* was the simple RE an unbackslashed $? */
713 p_simp_re(struct parse *p, struct branchc *bc)
722 # define BACKSL (1<<CHAR_BIT)
724 pos = HERE(); /* repetition op, if any, covers from here */
726 assert(MORE()); /* caller should have ensured this */
729 (void)REQUIRE(MORE(), REG_EESCAPE);
730 c = BACKSL | GETNEXT();
734 if (p->g->cflags®_NEWLINE)
749 SETERROR(REG_BADRPT);
755 p->pbegin[subno] = HERE();
756 EMIT(OLPAREN, subno);
757 /* the MORE here is an error heuristic */
758 if (MORE() && !SEETWO('\\', ')'))
760 if (subno < NPAREN) {
761 p->pend[subno] = HERE();
762 assert(p->pend[subno] != 0);
764 EMIT(ORPAREN, subno);
765 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
767 case BACKSL|')': /* should not get here -- must be user */
768 SETERROR(REG_EPAREN);
779 i = (c&~BACKSL) - '0';
781 if (p->pend[i] != 0) {
782 assert(i <= p->g->nsub);
784 assert(p->pbegin[i] != 0);
785 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
786 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
787 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
790 SETERROR(REG_ESUBREG);
795 * Ordinary if used as the first character beyond BOL anchor of
796 * a (sub-)expression, counts as a bad repetition operator if it
799 (void)REQUIRE(bc->nchain == 0, REG_BADRPT);
803 return (false); /* Definitely not $... */
810 if (EAT('*')) { /* implemented as +? */
811 /* this case does not require the (y|) trick, noKLUDGE */
814 INSERT(OQUEST_, pos);
815 ASTERN(O_QUEST, pos);
816 } else if (EATTWO('\\', '{')) {
819 if (MORE() && isdigit((uch)PEEK())) {
821 (void)REQUIRE(count <= count2, REG_BADBR);
822 } else /* single number with comma */
824 } else /* just a single number */
826 repeat(p, pos, count, count2);
827 if (!EATTWO('\\', '}')) { /* error heuristics */
828 while (MORE() && !SEETWO('\\', '}'))
830 (void)REQUIRE(MORE(), REG_EBRACE);
833 } else if (c == '$') /* $ (but not \$) ends it */
840 - p_count - parse a repetition count
841 == static int p_count(struct parse *p);
843 static int /* the value */
844 p_count(struct parse *p)
849 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
850 count = count*10 + (GETNEXT() - '0');
854 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
859 - p_bracket - parse a bracketed character list
860 == static void p_bracket(struct parse *p);
863 p_bracket(struct parse *p)
868 /* Dept of Truly Sickening Special-Case Kludges */
869 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
874 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
880 if ((cs = allocset(p)) == NULL)
883 if (p->g->cflags®_ICASE)
891 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
895 (void)MUSTEAT(']', REG_EBRACK);
897 if (p->error != 0) /* don't mess things up further */
900 if (cs->invert && p->g->cflags®_NEWLINE)
901 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
903 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
907 EMIT(OANYOF, (int)(cs - p->g->sets));
911 p_range_cmp(wchar_t c1, wchar_t c2)
914 return __wcollate_range_cmp(c1, c2);
916 /* Copied from libc/collate __wcollate_range_cmp */
917 wchar_t s1[2], s2[2];
923 return (wcscoll(s1, s2));
928 - p_b_term - parse one term of a bracketed character list
929 == static void p_b_term(struct parse *p, cset *cs);
932 p_b_term(struct parse *p, cset *cs)
935 wint_t start, finish;
938 struct xlocale_collate *table =
939 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
941 /* classify what we've got */
942 switch ((MORE()) ? PEEK() : '\0') {
944 c = (MORE2()) ? PEEK2() : '\0';
947 SETERROR(REG_ERANGE);
948 return; /* NOTE RETURN */
955 case ':': /* character class */
957 (void)REQUIRE(MORE(), REG_EBRACK);
959 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
961 (void)REQUIRE(MORE(), REG_EBRACK);
962 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
964 case '=': /* equivalence class */
966 (void)REQUIRE(MORE(), REG_EBRACK);
968 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
970 (void)REQUIRE(MORE(), REG_EBRACK);
971 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
973 default: /* symbol, ordinary character, or range */
974 start = p_b_symbol(p);
975 if (SEE('-') && MORE2() && PEEK2() != ']') {
981 finish = p_b_symbol(p);
988 if (table->__collate_load_error || MB_CUR_MAX > 1) {
990 if (MB_CUR_MAX > 1) {
992 (void)REQUIRE(start <= finish, REG_ERANGE);
993 CHaddrange(p, cs, start, finish);
995 (void)REQUIRE(p_range_cmp(start, finish) <= 0, REG_ERANGE);
996 for (i = 0; i <= UCHAR_MAX; i++) {
997 if (p_range_cmp(start, i) <= 0 &&
998 p_range_cmp(i, finish) <= 0 )
1008 - p_b_cclass - parse a character-class name and deal with it
1009 == static void p_b_cclass(struct parse *p, cset *cs);
1012 p_b_cclass(struct parse *p, cset *cs)
1014 const char *sp = p->next;
1019 while (MORE() && isalpha((uch)PEEK()))
1022 if (len >= sizeof(clname) - 1) {
1023 SETERROR(REG_ECTYPE);
1026 memcpy(clname, sp, len);
1028 if ((wct = wctype(clname)) == 0) {
1029 SETERROR(REG_ECTYPE);
1032 CHaddtype(p, cs, wct);
1036 - p_b_eclass - parse an equivalence-class name and deal with it
1037 == static void p_b_eclass(struct parse *p, cset *cs);
1039 * This implementation is incomplete. xxx
1042 p_b_eclass(struct parse *p, cset *cs)
1046 c = p_b_coll_elem(p, '=');
1051 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
1052 == static wint_t p_b_symbol(struct parse *p);
1054 static wint_t /* value of symbol */
1055 p_b_symbol(struct parse *p)
1059 (void)REQUIRE(MORE(), REG_EBRACK);
1060 if (!EATTWO('[', '.'))
1063 /* collating symbol */
1064 value = p_b_coll_elem(p, '.');
1065 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1070 - p_b_coll_elem - parse a collating-element name and look it up
1071 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
1073 static wint_t /* value of collating element */
1074 p_b_coll_elem(struct parse *p,
1075 wint_t endc) /* name ended by endc,']' */
1077 const char *sp = p->next;
1083 while (MORE() && !SEETWO(endc, ']'))
1086 SETERROR(REG_EBRACK);
1090 for (cp = cnames; cp->name != NULL; cp++)
1091 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1092 return(cp->code); /* known name */
1093 memset(&mbs, 0, sizeof(mbs));
1094 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
1095 return (wc); /* single character */
1096 else if (clen == (size_t)-1 || clen == (size_t)-2)
1097 SETERROR(REG_ILLSEQ);
1099 SETERROR(REG_ECOLLATE); /* neither */
1104 - othercase - return the case counterpart of an alphabetic
1105 == static wint_t othercase(wint_t ch);
1107 static wint_t /* if no counterpart, return ch */
1108 othercase(wint_t ch)
1110 assert(iswalpha(ch));
1112 return(towlower(ch));
1113 else if (iswlower(ch))
1114 return(towupper(ch));
1115 else /* peculiar, but could happen */
1120 - bothcases - emit a dualcase version of a two-case character
1121 == static void bothcases(struct parse *p, wint_t ch);
1123 * Boy, is this implementation ever a kludge...
1126 bothcases(struct parse *p, wint_t ch)
1128 const char *oldnext = p->next;
1129 const char *oldend = p->end;
1130 char bracket[3 + MB_LEN_MAX];
1134 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1136 memset(&mbs, 0, sizeof(mbs));
1137 n = wcrtomb(bracket, ch, &mbs);
1138 assert(n != (size_t)-1);
1140 bracket[n + 1] = '\0';
1141 p->end = bracket+n+1;
1143 assert(p->next == p->end);
1149 - ordinary - emit an ordinary character
1150 == static void ordinary(struct parse *p, wint_t ch);
1153 ordinary(struct parse *p, wint_t ch)
1157 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
1159 else if ((ch & OPDMASK) == ch)
1163 * Kludge: character is too big to fit into an OCHAR operand.
1164 * Emit a singleton set.
1166 if ((cs = allocset(p)) == NULL)
1169 EMIT(OANYOF, (int)(cs - p->g->sets));
1174 - nonnewline - emit REG_NEWLINE version of OANY
1175 == static void nonnewline(struct parse *p);
1177 * Boy, is this implementation ever a kludge...
1180 nonnewline(struct parse *p)
1182 const char *oldnext = p->next;
1183 const char *oldend = p->end;
1193 assert(p->next == bracket+3);
1199 - repeat - generate code for a bounded repetition, recursively if needed
1200 == static void repeat(struct parse *p, sopno start, int from, int to);
1203 repeat(struct parse *p,
1204 sopno start, /* operand from here to end of strip */
1205 int from, /* repeated from this number */
1206 int to) /* to this number of times (maybe INFINITY) */
1208 sopno finish = HERE();
1211 # define REP(f, t) ((f)*8 + (t))
1212 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1215 if (p->error != 0) /* head off possible runaway recursion */
1220 switch (REP(MAP(from), MAP(to))) {
1221 case REP(0, 0): /* must be user doing this */
1222 DROP(finish-start); /* drop the operand */
1224 case REP(0, 1): /* as x{1,1}? */
1225 case REP(0, N): /* as x{1,n}? */
1226 case REP(0, INF): /* as x{1,}? */
1227 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1228 INSERT(OCH_, start); /* offset is wrong... */
1229 repeat(p, start+1, 1, to);
1230 ASTERN(OOR1, start);
1231 AHEAD(start); /* ... fix it */
1234 ASTERN(O_CH, THERETHERE());
1236 case REP(1, 1): /* trivial case */
1239 case REP(1, N): /* as x?x{1,n-1} */
1240 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1241 INSERT(OCH_, start);
1242 ASTERN(OOR1, start);
1244 EMIT(OOR2, 0); /* offset very wrong... */
1245 AHEAD(THERE()); /* ...so fix it */
1246 ASTERN(O_CH, THERETHERE());
1247 copy = dupl(p, start+1, finish+1);
1248 assert(copy == finish+4);
1249 repeat(p, copy, 1, to-1);
1251 case REP(1, INF): /* as x+ */
1252 INSERT(OPLUS_, start);
1253 ASTERN(O_PLUS, start);
1255 case REP(N, N): /* as xx{m-1,n-1} */
1256 copy = dupl(p, start, finish);
1257 repeat(p, copy, from-1, to-1);
1259 case REP(N, INF): /* as xx{n-1,INF} */
1260 copy = dupl(p, start, finish);
1261 repeat(p, copy, from-1, to);
1263 default: /* "can't happen" */
1264 SETERROR(REG_ASSERT); /* just in case */
1270 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1271 - character from the parse struct, signals a REG_ILLSEQ error if the
1272 - character can't be converted. Returns the number of bytes consumed.
1275 wgetnext(struct parse *p)
1281 memset(&mbs, 0, sizeof(mbs));
1282 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1283 if (n == (size_t)-1 || n == (size_t)-2) {
1284 SETERROR(REG_ILLSEQ);
1294 - seterr - set an error condition
1295 == static int seterr(struct parse *p, int e);
1297 static int /* useless but makes type checking happy */
1298 seterr(struct parse *p, int e)
1300 if (p->error == 0) /* keep earliest error condition */
1302 p->next = nuls; /* try to bring things to a halt */
1304 return(0); /* make the return value well-defined */
1308 - allocset - allocate a set of characters for []
1309 == static cset *allocset(struct parse *p);
1312 allocset(struct parse *p)
1316 ncs = reallocarray(p->g->sets, p->g->ncsets + 1, sizeof(*ncs));
1318 SETERROR(REG_ESPACE);
1322 cs = &p->g->sets[p->g->ncsets++];
1323 memset(cs, 0, sizeof(*cs));
1329 - freeset - free a now-unused set
1330 == static void freeset(struct parse *p, cset *cs);
1333 freeset(struct parse *p, cset *cs)
1335 cset *top = &p->g->sets[p->g->ncsets];
1340 memset(cs, 0, sizeof(*cs));
1341 if (cs == top-1) /* recover only the easy case */
1346 - singleton - Determine whether a set contains only one character,
1347 - returning it if so, otherwise returning OUT.
1354 for (i = n = 0; i < NC; i++)
1361 if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 &&
1363 return (cs->wides[0]);
1364 /* Don't bother handling the other cases. */
1369 - CHadd - add character to character set.
1372 CHadd(struct parse *p, cset *cs, wint_t ch)
1374 wint_t nch, *newwides;
1377 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1379 newwides = reallocarray(cs->wides, cs->nwides + 1,
1380 sizeof(*cs->wides));
1381 if (newwides == NULL) {
1382 SETERROR(REG_ESPACE);
1385 cs->wides = newwides;
1386 cs->wides[cs->nwides++] = ch;
1389 if ((nch = towlower(ch)) < NC)
1390 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1391 if ((nch = towupper(ch)) < NC)
1392 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1397 - CHaddrange - add all characters in the range [min,max] to a character set.
1400 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1404 for (; min < NC && min <= max; min++)
1408 newranges = reallocarray(cs->ranges, cs->nranges + 1,
1409 sizeof(*cs->ranges));
1410 if (newranges == NULL) {
1411 SETERROR(REG_ESPACE);
1414 cs->ranges = newranges;
1415 cs->ranges[cs->nranges].min = min;
1416 cs->ranges[cs->nranges].max = max;
1421 - CHaddtype - add all characters of a certain type to a character set.
1424 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1429 for (i = 0; i < NC; i++)
1430 if (iswctype(i, wct))
1432 newtypes = reallocarray(cs->types, cs->ntypes + 1,
1433 sizeof(*cs->types));
1434 if (newtypes == NULL) {
1435 SETERROR(REG_ESPACE);
1438 cs->types = newtypes;
1439 cs->types[cs->ntypes++] = wct;
1443 - dupl - emit a duplicate of a bunch of sops
1444 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1446 static sopno /* start of duplicate */
1447 dupl(struct parse *p,
1448 sopno start, /* from here */
1449 sopno finish) /* to this less one */
1452 sopno len = finish - start;
1454 assert(finish >= start);
1457 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1459 (void) memcpy((char *)(p->strip + p->slen),
1460 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1466 - doemit - emit a strip operator
1467 == static void doemit(struct parse *p, sop op, size_t opnd);
1469 * It might seem better to implement this as a macro with a function as
1470 * hard-case backup, but it's just too big and messy unless there are
1471 * some changes to the data structures. Maybe later.
1474 doemit(struct parse *p, sop op, size_t opnd)
1476 /* avoid making error situations worse */
1480 /* deal with oversize operands ("can't happen", more or less) */
1481 assert(opnd < 1<<OPSHIFT);
1483 /* deal with undersized strip */
1484 if (p->slen >= p->ssize)
1485 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1488 /* finally, it's all reduced to the easy case */
1489 p->strip[p->slen++] = SOP(op, opnd);
1493 - doinsert - insert a sop into the strip
1494 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1497 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1503 /* avoid making error situations worse */
1508 EMIT(op, opnd); /* do checks, ensure space */
1509 assert(HERE() == sn+1);
1512 /* adjust paren pointers */
1514 for (i = 1; i < NPAREN; i++) {
1515 if (p->pbegin[i] >= pos) {
1518 if (p->pend[i] >= pos) {
1523 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1524 (HERE()-pos-1)*sizeof(sop));
1529 - dofwd - complete a forward reference
1530 == static void dofwd(struct parse *p, sopno pos, sop value);
1533 dofwd(struct parse *p, sopno pos, sop value)
1535 /* avoid making error situations worse */
1539 assert(value < 1<<OPSHIFT);
1540 p->strip[pos] = OP(p->strip[pos]) | value;
1544 - enlarge - enlarge the strip
1545 == static int enlarge(struct parse *p, sopno size);
1548 enlarge(struct parse *p, sopno size)
1552 if (p->ssize >= size)
1555 sp = reallocarray(p->strip, size, sizeof(sop));
1557 SETERROR(REG_ESPACE);
1566 - stripsnug - compact the strip
1567 == static void stripsnug(struct parse *p, struct re_guts *g);
1570 stripsnug(struct parse *p, struct re_guts *g)
1572 g->nstates = p->slen;
1573 g->strip = reallocarray((char *)p->strip, p->slen, sizeof(sop));
1574 if (g->strip == NULL) {
1575 SETERROR(REG_ESPACE);
1576 g->strip = p->strip;
1581 - findmust - fill in must and mlen with longest mandatory literal string
1582 == static void findmust(struct parse *p, struct re_guts *g);
1584 * This algorithm could do fancy things like analyzing the operands of |
1585 * for common subsequences. Someday. This code is simple and finds most
1586 * of the interesting cases.
1588 * Note that must and mlen got initialized during setup.
1591 findmust(struct parse *p, struct re_guts *g)
1595 sop *newstart = NULL;
1600 char buf[MB_LEN_MAX];
1604 /* avoid making error situations worse */
1609 * It's not generally safe to do a ``char'' substring search on
1610 * multibyte character strings, but it's safe for at least
1611 * UTF-8 (see RFC 3629).
1613 if (MB_CUR_MAX > 1 &&
1614 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1617 /* find the longest OCHAR sequence in strip */
1621 scan = g->strip + 1;
1625 case OCHAR: /* sequence member */
1626 if (newlen == 0) { /* new sequence */
1627 memset(&mbs, 0, sizeof(mbs));
1628 newstart = scan - 1;
1630 clen = wcrtomb(buf, OPND(s), &mbs);
1631 if (clen == (size_t)-1)
1635 case OPLUS_: /* things that don't break one */
1639 case OQUEST_: /* things that must be skipped */
1641 offset = altoffset(scan, offset);
1646 /* assert() interferes w debug printouts */
1647 if (OP(s) != (sop)O_QUEST &&
1648 OP(s) != (sop)O_CH && OP(s) != (sop)OOR2) {
1652 } while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH);
1654 case OBOW: /* things that break a sequence */
1661 if (newlen > (sopno)g->mlen) { /* ends one */
1665 g->moffset += offset;
1668 g->moffset = offset;
1676 if (newlen > (sopno)g->mlen) { /* ends one */
1680 g->moffset += offset;
1683 g->moffset = offset;
1692 case OANYOF: /* may or may not invalidate offset */
1693 /* First, everything as OANY */
1694 if (newlen > (sopno)g->mlen) { /* ends one */
1698 g->moffset += offset;
1701 g->moffset = offset;
1712 /* Anything here makes it impossible or too hard
1713 * to calculate the offset -- so we give up;
1714 * save the last known good offset, in case the
1715 * must sequence doesn't occur later.
1717 if (newlen > (sopno)g->mlen) { /* ends one */
1721 g->moffset += offset;
1723 g->moffset = offset;
1729 } while (OP(s) != OEND);
1731 if (g->mlen == 0) { /* there isn't one */
1736 /* turn it into a character string */
1737 g->must = malloc((size_t)g->mlen + 1);
1738 if (g->must == NULL) { /* argh; just forget it */
1745 memset(&mbs, 0, sizeof(mbs));
1746 while (cp < g->must + g->mlen) {
1747 while (OP(s = *scan++) != OCHAR)
1749 clen = wcrtomb(cp, OPND(s), &mbs);
1750 assert(clen != (size_t)-1);
1753 assert(cp == g->must + g->mlen);
1754 *cp++ = '\0'; /* just on general principles */
1758 - altoffset - choose biggest offset among multiple choices
1759 == static int altoffset(sop *scan, int offset);
1761 * Compute, recursively if necessary, the largest offset among multiple
1765 altoffset(sop *scan, int offset)
1771 /* If we gave up already on offsets, return */
1778 while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH) {
1787 try = altoffset(scan, try);
1794 if (OP(s) != (sop)O_QUEST &&
1795 OP(s) != (sop)O_CH && OP(s) != (sop)OOR2)
1797 } while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH);
1798 /* We must skip to the next position, or we'll
1799 * leave altoffset() too early.
1825 return largest+offset;
1829 - computejumps - compute char jumps for BM scan
1830 == static void computejumps(struct parse *p, struct re_guts *g);
1832 * This algorithm assumes g->must exists and is has size greater than
1833 * zero. It's based on the algorithm found on Computer Algorithms by
1836 * A char jump is the number of characters one needs to jump based on
1837 * the value of the character from the text that was mismatched.
1840 computejumps(struct parse *p, struct re_guts *g)
1845 /* Avoid making errors worse */
1849 g->charjump = (int *)malloc((NC_MAX + 1) * sizeof(int));
1850 if (g->charjump == NULL) /* Not a fatal error */
1852 /* Adjust for signed chars, if necessary */
1853 g->charjump = &g->charjump[-(CHAR_MIN)];
1855 /* If the character does not exist in the pattern, the jump
1856 * is equal to the number of characters in the pattern.
1858 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1859 g->charjump[ch] = g->mlen;
1861 /* If the character does exist, compute the jump that would
1862 * take us to the last character in the pattern equal to it
1863 * (notice that we match right to left, so that last character
1864 * is the first one that would be matched).
1866 for (mindex = 0; mindex < g->mlen; mindex++)
1867 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
1871 - computematchjumps - compute match jumps for BM scan
1872 == static void computematchjumps(struct parse *p, struct re_guts *g);
1874 * This algorithm assumes g->must exists and is has size greater than
1875 * zero. It's based on the algorithm found on Computer Algorithms by
1878 * A match jump is the number of characters one needs to advance based
1879 * on the already-matched suffix.
1880 * Notice that all values here are minus (g->mlen-1), because of the way
1881 * the search algorithm works.
1884 computematchjumps(struct parse *p, struct re_guts *g)
1886 int mindex; /* General "must" iterator */
1887 int suffix; /* Keeps track of matching suffix */
1888 int ssuffix; /* Keeps track of suffixes' suffix */
1889 int* pmatches; /* pmatches[k] points to the next i
1890 * such that i+1...mlen is a substring
1891 * of k+1...k+mlen-i-1
1894 /* Avoid making errors worse */
1898 pmatches = (int*) malloc(g->mlen * sizeof(int));
1899 if (pmatches == NULL) {
1900 g->matchjump = NULL;
1904 g->matchjump = (int*) malloc(g->mlen * sizeof(int));
1905 if (g->matchjump == NULL) { /* Not a fatal error */
1910 /* Set maximum possible jump for each character in the pattern */
1911 for (mindex = 0; mindex < g->mlen; mindex++)
1912 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
1914 /* Compute pmatches[] */
1915 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
1916 mindex--, suffix--) {
1917 pmatches[mindex] = suffix;
1919 /* If a mismatch is found, interrupting the substring,
1920 * compute the matchjump for that position. If no
1921 * mismatch is found, then a text substring mismatched
1922 * against the suffix will also mismatch against the
1925 while (suffix < g->mlen
1926 && g->must[mindex] != g->must[suffix]) {
1927 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1928 g->mlen - mindex - 1);
1929 suffix = pmatches[suffix];
1933 /* Compute the matchjump up to the last substring found to jump
1934 * to the beginning of the largest must pattern prefix matching
1937 for (mindex = 0; mindex <= suffix; mindex++)
1938 g->matchjump[mindex] = MIN(g->matchjump[mindex],
1939 g->mlen + suffix - mindex);
1941 ssuffix = pmatches[suffix];
1942 while (suffix < g->mlen) {
1943 while (suffix <= ssuffix && suffix < g->mlen) {
1944 g->matchjump[suffix] = MIN(g->matchjump[suffix],
1945 g->mlen + ssuffix - suffix);
1948 if (suffix < g->mlen)
1949 ssuffix = pmatches[ssuffix];
1956 - pluscount - count + nesting
1957 == static sopno pluscount(struct parse *p, struct re_guts *g);
1959 static sopno /* nesting depth */
1960 pluscount(struct parse *p, struct re_guts *g)
1968 return(0); /* there may not be an OEND */
1970 scan = g->strip + 1;
1978 if (plusnest > maxnest)
1983 } while (OP(s) != OEND);