]>
git.saurik.com Git - apple/libc.git/blob - regex/FreeBSD/regcomp.c
2 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
40 #if defined(LIBC_SCCS) && !defined(lint)
41 static char sccsid
[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
42 #endif /* LIBC_SCCS and not lint */
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD: src/lib/libc/regex/regcomp.c,v 1.34 2004/10/03 15:42:59 stefanf Exp $");
46 #include <sys/types.h>
65 * parse structure, passed up and down to avoid global variables and
69 char *next
; /* next character in RE */
70 char *end
; /* end of string (-> NUL normally) */
71 int error
; /* has an error been seen? */
72 sop
*strip
; /* malloced strip */
73 sopno ssize
; /* malloced strip size (allocated) */
74 sopno slen
; /* malloced strip length (used) */
75 int ncsalloc
; /* number of csets allocated */
77 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
78 sopno pbegin
[NPAREN
]; /* -> ( ([0] unused) */
79 sopno pend
[NPAREN
]; /* -> ) ([0] unused) */
82 /* ========= begin header generated by ./mkh ========= */
87 /* === regcomp.c === */
88 static void p_ere(struct parse
*p
, wint_t stop
);
89 static void p_ere_exp(struct parse
*p
);
90 static void p_str(struct parse
*p
);
91 static void p_bre(struct parse
*p
, wint_t end1
, wint_t end2
);
92 static int p_simp_re(struct parse
*p
, int starordinary
);
93 static int p_count(struct parse
*p
);
94 static void p_bracket(struct parse
*p
);
95 static void p_b_term(struct parse
*p
, cset
*cs
);
96 static void p_b_cclass(struct parse
*p
, cset
*cs
);
97 static void p_b_eclass(struct parse
*p
, cset
*cs
);
98 static wint_t p_b_symbol(struct parse
*p
);
99 static wint_t p_b_coll_elem(struct parse
*p
, wint_t endc
);
100 static wint_t othercase(wint_t ch
);
101 static void bothcases(struct parse
*p
, wint_t ch
);
102 static void ordinary(struct parse
*p
, wint_t ch
);
103 static void nonnewline(struct parse
*p
);
104 static void repeat(struct parse
*p
, sopno start
, int from
, int to
);
105 static int seterr(struct parse
*p
, int e
);
106 static cset
*allocset(struct parse
*p
);
107 static void freeset(struct parse
*p
, cset
*cs
);
108 static void CHadd(struct parse
*p
, cset
*cs
, wint_t ch
);
109 static void CHaddrange(struct parse
*p
, cset
*cs
, wint_t min
, wint_t max
);
110 static void CHaddtype(struct parse
*p
, cset
*cs
, wctype_t wct
);
111 static wint_t singleton(cset
*cs
);
112 static sopno
dupl(struct parse
*p
, sopno start
, sopno finish
);
113 static void doemit(struct parse
*p
, sop op
, size_t opnd
);
114 static void doinsert(struct parse
*p
, sop op
, size_t opnd
, sopno pos
);
115 static void dofwd(struct parse
*p
, sopno pos
, sop value
);
116 static void enlarge(struct parse
*p
, sopno size
);
117 static void stripsnug(struct parse
*p
, struct re_guts
*g
);
118 static void findmust(struct parse
*p
, struct re_guts
*g
);
119 static int altoffset(sop
*scan
, int offset
);
120 static void computejumps(struct parse
*p
, struct re_guts
*g
);
121 static void computematchjumps(struct parse
*p
, struct re_guts
*g
);
122 static sopno
pluscount(struct parse
*p
, struct re_guts
*g
);
123 static wint_t wgetnext(struct parse
*p
);
128 /* ========= end header generated by ./mkh ========= */
130 static char nuls
[10]; /* place to point scanner in event of error */
133 * macros for use with parse structure
134 * BEWARE: these know that the parse structure is named `p' !!!
136 #define PEEK() (*p->next)
137 #define PEEK2() (*(p->next+1))
138 #define MORE() (p->next < p->end)
139 #define MORE2() (p->next+1 < p->end)
140 #define SEE(c) (MORE() && PEEK() == (c))
141 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
142 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
143 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
144 #define NEXT() (p->next++)
145 #define NEXT2() (p->next += 2)
146 #define NEXTn(n) (p->next += (n))
147 #define GETNEXT() (*p->next++)
148 #define WGETNEXT() wgetnext(p)
149 #define SETERROR(e) seterr(p, (e))
150 #define REQUIRE(co, e) ((co) || SETERROR(e))
151 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
152 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
153 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
154 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
155 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
156 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
157 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
158 #define HERE() (p->slen)
159 #define THERE() (p->slen - 1)
160 #define THERETHERE() (p->slen - 2)
161 #define DROP(n) (p->slen -= (n))
164 static int never
= 0; /* for use in asserts; shuts lint up */
166 #define never 0 /* some <assert.h>s have bugs too */
169 /* Macro used by computejump()/computematchjump() */
170 #define MIN(a,b) ((a)<(b)?(a):(b))
173 - regcomp - interface for parser and compilation
174 = extern int regcomp(regex_t *, const char *, int);
175 = #define REG_BASIC 0000
176 = #define REG_EXTENDED 0001
177 = #define REG_ICASE 0002
178 = #define REG_NOSUB 0004
179 = #define REG_NEWLINE 0010
180 = #define REG_NOSPEC 0020
181 = #define REG_PEND 0040
182 = #define REG_DUMP 0200
184 int /* 0 success, otherwise REG_something */
185 regcomp(preg
, pattern
, cflags
)
186 regex_t
* __restrict preg
;
187 const char * __restrict pattern
;
192 struct parse
*p
= &pa
;
196 # define GOODFLAGS(f) (f)
198 # define GOODFLAGS(f) ((f)&~REG_DUMP)
201 cflags
= GOODFLAGS(cflags
);
202 if ((cflags
®_EXTENDED
) && (cflags
®_NOSPEC
))
205 if (cflags
®_PEND
) {
206 if (preg
->re_endp
< pattern
)
208 len
= preg
->re_endp
- pattern
;
210 len
= strlen((char *)pattern
);
212 /* do the mallocs early so failure handling is easy */
213 g
= (struct re_guts
*)malloc(sizeof(struct re_guts
));
216 p
->ssize
= len
/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
217 p
->strip
= (sop
*)malloc(p
->ssize
* sizeof(sop
));
219 if (p
->strip
== NULL
) {
226 p
->next
= (char *)pattern
; /* convenience; we do not modify it */
227 p
->end
= p
->next
+ len
;
230 for (i
= 0; i
< NPAREN
; i
++) {
250 g
->firststate
= THERE();
251 if (cflags
®_EXTENDED
)
253 else if (cflags
®_NOSPEC
)
258 g
->laststate
= THERE();
260 /* tidy up loose ends and fill things in */
263 /* only use Boyer-Moore algorithm if the pattern is bigger
264 * than three characters
268 computematchjumps(p
, g
);
269 if(g
->matchjump
== NULL
&& g
->charjump
!= NULL
) {
274 g
->nplus
= pluscount(p
, g
);
276 preg
->re_nsub
= g
->nsub
;
278 preg
->re_magic
= MAGIC1
;
280 /* not debugging, so can't rely on the assert() in regexec() */
282 SETERROR(REG_ASSERT
);
285 /* win or lose, we're done */
286 if (p
->error
!= 0) /* lose */
292 - p_ere - ERE parser top level, concatenation and alternation
293 == static void p_ere(struct parse *p, int stop);
298 int stop
; /* character this ERE should end at */
304 int first
= 1; /* is this the first alternative? */
307 /* do a bunch of concatenated expressions */
309 while (MORE() && (c
= PEEK()) != '|' && c
!= stop
)
311 (void)REQUIRE(HERE() != conc
, REG_EMPTY
); /* require nonempty */
314 break; /* NOTE BREAK OUT */
317 INSERT(OCH_
, conc
); /* offset is wrong */
322 ASTERN(OOR1
, prevback
);
324 AHEAD(prevfwd
); /* fix previous offset */
326 EMIT(OOR2
, 0); /* offset is very wrong */
329 if (!first
) { /* tail-end fixups */
331 ASTERN(O_CH
, prevback
);
334 assert(!MORE() || SEE(stop
));
338 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
339 == static void p_ere_exp(struct parse *p);
353 assert(MORE()); /* caller should have ensured this */
359 (void)REQUIRE(MORE(), REG_EPAREN
);
363 p
->pbegin
[subno
] = HERE();
364 EMIT(OLPAREN
, subno
);
367 if (subno
< NPAREN
) {
368 p
->pend
[subno
] = HERE();
369 assert(p
->pend
[subno
] != 0);
371 EMIT(ORPAREN
, subno
);
372 (void)MUSTEAT(')', REG_EPAREN
);
374 #ifndef POSIX_MISTAKE
375 case ')': /* happens only if no current unmatched ( */
377 * You may ask, why the ifndef? Because I didn't notice
378 * this until slightly too late for 1003.2, and none of the
379 * other 1003.2 regular-expression reviewers noticed it at
380 * all. So an unmatched ) is legal POSIX, at least until
381 * we can get it fixed.
383 SETERROR(REG_EPAREN
);
388 p
->g
->iflags
|= USEBOL
;
394 p
->g
->iflags
|= USEEOL
;
403 SETERROR(REG_BADRPT
);
406 if (p
->g
->cflags
®_NEWLINE
)
415 (void)REQUIRE(MORE(), REG_EESCAPE
);
419 case '{': /* okay as ordinary except if digit follows */
420 (void)REQUIRE(!MORE() || !isdigit((uch
)PEEK()), REG_BADRPT
);
432 /* we call { a repetition if followed by a digit */
433 if (!( c
== '*' || c
== '+' || c
== '?' ||
434 (c
== '{' && MORE2() && isdigit((uch
)PEEK2())) ))
435 return; /* no repetition, we're done */
438 (void)REQUIRE(!wascaret
, REG_BADRPT
);
440 case '*': /* implemented as +? */
441 /* this case does not require the (y|) trick, noKLUDGE */
444 INSERT(OQUEST_
, pos
);
445 ASTERN(O_QUEST
, pos
);
452 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
453 INSERT(OCH_
, pos
); /* offset slightly wrong */
454 ASTERN(OOR1
, pos
); /* this one's right */
455 AHEAD(pos
); /* fix the OCH_ */
456 EMIT(OOR2
, 0); /* offset very wrong... */
457 AHEAD(THERE()); /* ...so fix it */
458 ASTERN(O_CH
, THERETHERE());
463 if (isdigit((uch
)PEEK())) {
465 (void)REQUIRE(count
<= count2
, REG_BADBR
);
466 } else /* single number with comma */
468 } else /* just a single number */
470 repeat(p
, pos
, count
, count2
);
471 if (!EAT('}')) { /* error heuristics */
472 while (MORE() && PEEK() != '}')
474 (void)REQUIRE(MORE(), REG_EBRACE
);
483 if (!( c
== '*' || c
== '+' || c
== '?' ||
484 (c
== '{' && MORE2() && isdigit((uch
)PEEK2())) ) )
486 SETERROR(REG_BADRPT
);
490 - p_str - string (no metacharacters) "parser"
491 == static void p_str(struct parse *p);
497 (void)REQUIRE(MORE(), REG_EMPTY
);
499 ordinary(p
, WGETNEXT());
503 - p_bre - BRE parser top level, anchoring and concatenation
504 == static void p_bre(struct parse *p, int end1, \
506 * Giving end1 as OUT essentially eliminates the end1/end2 check.
508 * This implementation is a bit of a kludge, in that a trailing $ is first
509 * taken as an ordinary character and then revised to be an anchor.
510 * The amount of lookahead needed to avoid this kludge is excessive.
515 int end1
; /* first terminating character */
516 int end2
; /* second terminating character */
518 sopno start
= HERE();
519 int first
= 1; /* first subexpression? */
524 p
->g
->iflags
|= USEBOL
;
527 while (MORE() && !SEETWO(end1
, end2
)) {
528 wasdollar
= p_simp_re(p
, first
);
531 if (wasdollar
) { /* oops, that was a trailing anchor */
534 p
->g
->iflags
|= USEEOL
;
538 (void)REQUIRE(HERE() != start
, REG_EMPTY
); /* require nonempty */
542 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
543 == static int p_simp_re(struct parse *p, int starordinary);
545 static int /* was the simple RE an unbackslashed $? */
546 p_simp_re(p
, starordinary
)
548 int starordinary
; /* is a leading * an ordinary character? */
557 # define BACKSL (1<<CHAR_BIT)
559 pos
= HERE(); /* repetion op, if any, covers from here */
561 assert(MORE()); /* caller should have ensured this */
564 (void)REQUIRE(MORE(), REG_EESCAPE
);
565 c
= BACKSL
| GETNEXT();
569 if (p
->g
->cflags
®_NEWLINE
)
578 SETERROR(REG_BADRPT
);
584 p
->pbegin
[subno
] = HERE();
585 EMIT(OLPAREN
, subno
);
586 /* the MORE here is an error heuristic */
587 if (MORE() && !SEETWO('\\', ')'))
589 if (subno
< NPAREN
) {
590 p
->pend
[subno
] = HERE();
591 assert(p
->pend
[subno
] != 0);
593 EMIT(ORPAREN
, subno
);
594 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN
);
596 case BACKSL
|')': /* should not get here -- must be user */
598 SETERROR(REG_EPAREN
);
609 i
= (c
&~BACKSL
) - '0';
611 if (p
->pend
[i
] != 0) {
612 assert(i
<= p
->g
->nsub
);
614 assert(p
->pbegin
[i
] != 0);
615 assert(OP(p
->strip
[p
->pbegin
[i
]]) == OLPAREN
);
616 assert(OP(p
->strip
[p
->pend
[i
]]) == ORPAREN
);
617 (void) dupl(p
, p
->pbegin
[i
]+1, p
->pend
[i
]);
620 SETERROR(REG_ESUBREG
);
624 (void)REQUIRE(starordinary
, REG_BADRPT
);
633 if (EAT('*')) { /* implemented as +? */
634 /* this case does not require the (y|) trick, noKLUDGE */
637 INSERT(OQUEST_
, pos
);
638 ASTERN(O_QUEST
, pos
);
639 } else if (EATTWO('\\', '{')) {
642 if (MORE() && isdigit((uch
)PEEK())) {
644 (void)REQUIRE(count
<= count2
, REG_BADBR
);
645 } else /* single number with comma */
647 } else /* just a single number */
649 repeat(p
, pos
, count
, count2
);
650 if (!EATTWO('\\', '}')) { /* error heuristics */
651 while (MORE() && !SEETWO('\\', '}'))
653 (void)REQUIRE(MORE(), REG_EBRACE
);
656 } else if (c
== '$') /* $ (but not \$) ends it */
663 - p_count - parse a repetition count
664 == static int p_count(struct parse *p);
666 static int /* the value */
673 while (MORE() && isdigit((uch
)PEEK()) && count
<= DUPMAX
) {
674 count
= count
*10 + (GETNEXT() - '0');
678 (void)REQUIRE(ndigits
> 0 && count
<= DUPMAX
, REG_BADBR
);
683 - p_bracket - parse a bracketed character list
684 == static void p_bracket(struct parse *p);
693 /* Dept of Truly Sickening Special-Case Kludges */
694 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:<:]]", 6) == 0) {
699 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:>:]]", 6) == 0) {
705 if ((cs
= allocset(p
)) == NULL
)
708 if (p
->g
->cflags
®_ICASE
)
716 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
720 (void)MUSTEAT(']', REG_EBRACK
);
722 if (p
->error
!= 0) /* don't mess things up further */
725 if (cs
->invert
&& p
->g
->cflags
®_NEWLINE
)
726 cs
->bmp
['\n' >> 3] |= 1 << ('\n' & 7);
728 if ((ch
= singleton(cs
)) != OUT
) { /* optimize singleton sets */
732 EMIT(OANYOF
, (int)(cs
- p
->g
->sets
));
736 - p_b_term - parse one term of a bracketed character list
737 == static void p_b_term(struct parse *p, cset *cs);
745 wint_t start
, finish
;
748 /* classify what we've got */
749 switch ((MORE()) ? PEEK() : '\0') {
751 c
= (MORE2()) ? PEEK2() : '\0';
754 SETERROR(REG_ERANGE
);
755 return; /* NOTE RETURN */
763 case ':': /* character class */
765 (void)REQUIRE(MORE(), REG_EBRACK
);
767 (void)REQUIRE(c
!= '-' && c
!= ']', REG_ECTYPE
);
769 (void)REQUIRE(MORE(), REG_EBRACK
);
770 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE
);
772 case '=': /* equivalence class */
774 (void)REQUIRE(MORE(), REG_EBRACK
);
776 (void)REQUIRE(c
!= '-' && c
!= ']', REG_ECOLLATE
);
778 (void)REQUIRE(MORE(), REG_EBRACK
);
779 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE
);
781 default: /* symbol, ordinary character, or range */
782 start
= p_b_symbol(p
);
783 if (SEE('-') && MORE2() && PEEK2() != ']') {
789 finish
= p_b_symbol(p
);
795 if (__collate_load_error
) {
796 (void)REQUIRE((uch
)start
<= (uch
)finish
, REG_ERANGE
);
797 CHaddrange(p
, cs
, start
, finish
);
799 (void)REQUIRE(__collate_range_cmp(start
, finish
) <= 0, REG_ERANGE
);
800 for (i
= 0; i
<= UCHAR_MAX
; i
++) {
801 if ( __collate_range_cmp(start
, i
) <= 0
802 && __collate_range_cmp(i
, finish
) <= 0
813 - p_b_cclass - parse a character-class name and deal with it
814 == static void p_b_cclass(struct parse *p, cset *cs);
826 while (MORE() && isalpha((uch
)PEEK()))
829 if (len
>= sizeof(clname
) - 1) {
830 SETERROR(REG_ECTYPE
);
833 memcpy(clname
, sp
, len
);
835 if ((wct
= wctype(clname
)) == 0) {
836 SETERROR(REG_ECTYPE
);
839 CHaddtype(p
, cs
, wct
);
843 - p_b_eclass - parse an equivalence-class name and deal with it
844 == static void p_b_eclass(struct parse *p, cset *cs);
846 * This implementation is incomplete. xxx
855 c
= p_b_coll_elem(p
, '=');
860 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
861 == static char p_b_symbol(struct parse *p);
863 static wint_t /* value of symbol */
869 (void)REQUIRE(MORE(), REG_EBRACK
);
870 if (!EATTWO('[', '.'))
873 /* collating symbol */
874 value
= p_b_coll_elem(p
, '.');
875 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE
);
880 - p_b_coll_elem - parse a collating-element name and look it up
881 == static char p_b_coll_elem(struct parse *p, int endc);
883 static wint_t /* value of collating element */
884 p_b_coll_elem(p
, endc
)
886 wint_t endc
; /* name ended by endc,']' */
895 while (MORE() && !SEETWO(endc
, ']'))
898 SETERROR(REG_EBRACK
);
902 for (cp
= cnames
; cp
->name
!= NULL
; cp
++)
903 if (strncmp(cp
->name
, sp
, len
) == 0 && cp
->name
[len
] == '\0')
904 return(cp
->code
); /* known name */
905 memset(&mbs
, 0, sizeof(mbs
));
906 if ((clen
= mbrtowc(&wc
, sp
, len
, &mbs
)) == len
)
907 return (wc
); /* single character */
908 else if (clen
== (size_t)-1 || clen
== (size_t)-2)
909 SETERROR(REG_ILLSEQ
);
911 SETERROR(REG_ECOLLATE
); /* neither */
916 - othercase - return the case counterpart of an alphabetic
917 == static char othercase(int ch);
919 static wint_t /* if no counterpart, return ch */
923 assert(iswalpha(ch
));
925 return(towlower(ch
));
926 else if (iswlower(ch
))
927 return(towupper(ch
));
928 else /* peculiar, but could happen */
933 - bothcases - emit a dualcase version of a two-case character
934 == static void bothcases(struct parse *p, int ch);
936 * Boy, is this implementation ever a kludge...
943 char *oldnext
= p
->next
;
944 char *oldend
= p
->end
;
945 char bracket
[3 + MB_LEN_MAX
];
949 assert(othercase(ch
) != ch
); /* p_bracket() would recurse */
951 memset(&mbs
, 0, sizeof(mbs
));
952 n
= wcrtomb(bracket
, ch
, &mbs
);
953 assert(n
!= (size_t)-1);
955 bracket
[n
+ 1] = '\0';
956 p
->end
= bracket
+n
+1;
958 assert(p
->next
== p
->end
);
964 - ordinary - emit an ordinary character
965 == static void ordinary(struct parse *p, int ch);
974 if ((p
->g
->cflags
®_ICASE
) && iswalpha(ch
) && othercase(ch
) != ch
)
976 else if ((ch
& OPDMASK
) == ch
)
980 * Kludge: character is too big to fit into an OCHAR operand.
981 * Emit a singleton set.
983 if ((cs
= allocset(p
)) == NULL
)
986 EMIT(OANYOF
, (int)(cs
- p
->g
->sets
));
991 - nonnewline - emit REG_NEWLINE version of OANY
992 == static void nonnewline(struct parse *p);
994 * Boy, is this implementation ever a kludge...
1000 char *oldnext
= p
->next
;
1001 char *oldend
= p
->end
;
1011 assert(p
->next
== bracket
+3);
1017 - repeat - generate code for a bounded repetition, recursively if needed
1018 == static void repeat(struct parse *p, sopno start, int from, int to);
1021 repeat(p
, start
, from
, to
)
1023 sopno start
; /* operand from here to end of strip */
1024 int from
; /* repeated from this number */
1025 int to
; /* to this number of times (maybe INFINITY) */
1027 sopno finish
= HERE();
1030 # define REP(f, t) ((f)*8 + (t))
1031 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1034 if (p
->error
!= 0) /* head off possible runaway recursion */
1039 switch (REP(MAP(from
), MAP(to
))) {
1040 case REP(0, 0): /* must be user doing this */
1041 DROP(finish
-start
); /* drop the operand */
1043 case REP(0, 1): /* as x{1,1}? */
1044 case REP(0, N
): /* as x{1,n}? */
1045 case REP(0, INF
): /* as x{1,}? */
1046 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1047 INSERT(OCH_
, start
); /* offset is wrong... */
1048 repeat(p
, start
+1, 1, to
);
1049 ASTERN(OOR1
, start
);
1050 AHEAD(start
); /* ... fix it */
1053 ASTERN(O_CH
, THERETHERE());
1055 case REP(1, 1): /* trivial case */
1058 case REP(1, N
): /* as x?x{1,n-1} */
1059 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1060 INSERT(OCH_
, start
);
1061 ASTERN(OOR1
, start
);
1063 EMIT(OOR2
, 0); /* offset very wrong... */
1064 AHEAD(THERE()); /* ...so fix it */
1065 ASTERN(O_CH
, THERETHERE());
1066 copy
= dupl(p
, start
+1, finish
+1);
1067 assert(copy
== finish
+4);
1068 repeat(p
, copy
, 1, to
-1);
1070 case REP(1, INF
): /* as x+ */
1071 INSERT(OPLUS_
, start
);
1072 ASTERN(O_PLUS
, start
);
1074 case REP(N
, N
): /* as xx{m-1,n-1} */
1075 copy
= dupl(p
, start
, finish
);
1076 repeat(p
, copy
, from
-1, to
-1);
1078 case REP(N
, INF
): /* as xx{n-1,INF} */
1079 copy
= dupl(p
, start
, finish
);
1080 repeat(p
, copy
, from
-1, to
);
1082 default: /* "can't happen" */
1083 SETERROR(REG_ASSERT
); /* just in case */
1089 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1090 - character from the parse struct, signals a REG_ILLSEQ error if the
1091 - character can't be converted. Returns the number of bytes consumed.
1101 memset(&mbs
, 0, sizeof(mbs
));
1102 n
= mbrtowc(&wc
, p
->next
, p
->end
- p
->next
, &mbs
);
1103 if (n
== (size_t)-1 || n
== (size_t)-2) {
1104 SETERROR(REG_ILLSEQ
);
1114 - seterr - set an error condition
1115 == static int seterr(struct parse *p, int e);
1117 static int /* useless but makes type checking happy */
1122 if (p
->error
== 0) /* keep earliest error condition */
1124 p
->next
= nuls
; /* try to bring things to a halt */
1126 return(0); /* make the return value well-defined */
1130 - allocset - allocate a set of characters for []
1131 == static cset *allocset(struct parse *p);
1139 ncs
= realloc(p
->g
->sets
, (p
->g
->ncsets
+ 1) * sizeof(*ncs
));
1141 SETERROR(REG_ESPACE
);
1145 cs
= &p
->g
->sets
[p
->g
->ncsets
++];
1146 memset(cs
, 0, sizeof(*cs
));
1152 - freeset - free a now-unused set
1153 == static void freeset(struct parse *p, cset *cs);
1160 cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1165 memset(cs
, 0, sizeof(*cs
));
1166 if (cs
== top
-1) /* recover only the easy case */
1171 - singleton - Determine whether a set contains only one character,
1172 - returning it if so, otherwise returning OUT.
1180 for (i
= n
= 0; i
< NC
; i
++)
1187 if (cs
->nwides
== 1 && cs
->nranges
== 0 && cs
->ntypes
== 0 &&
1189 return (cs
->wides
[0]);
1190 /* Don't bother handling the other cases. */
1195 - CHadd - add character to character set.
1203 wint_t nch
, *newwides
;
1206 cs
->bmp
[ch
>> 3] |= 1 << (ch
& 7);
1208 newwides
= realloc(cs
->wides
, (cs
->nwides
+ 1) *
1209 sizeof(*cs
->wides
));
1210 if (newwides
== NULL
) {
1211 SETERROR(REG_ESPACE
);
1214 cs
->wides
= newwides
;
1215 cs
->wides
[cs
->nwides
++] = ch
;
1218 if ((nch
= towlower(ch
)) < NC
)
1219 cs
->bmp
[nch
>> 3] |= 1 << (nch
& 7);
1220 if ((nch
= towupper(ch
)) < NC
)
1221 cs
->bmp
[nch
>> 3] |= 1 << (nch
& 7);
1226 - CHaddrange - add all characters in the range [min,max] to a character set.
1229 CHaddrange(p
, cs
, min
, max
)
1236 for (; min
< NC
&& min
<= max
; min
++)
1240 newranges
= realloc(cs
->ranges
, (cs
->nranges
+ 1) *
1241 sizeof(*cs
->ranges
));
1242 if (newranges
== NULL
) {
1243 SETERROR(REG_ESPACE
);
1246 cs
->ranges
= newranges
;
1247 cs
->ranges
[cs
->nranges
].min
= min
;
1248 cs
->ranges
[cs
->nranges
].min
= max
;
1253 - CHaddtype - add all characters of a certain type to a character set.
1256 CHaddtype(p
, cs
, wct
)
1264 for (i
= 0; i
< NC
; i
++)
1265 if (iswctype(i
, wct
))
1267 newtypes
= realloc(cs
->types
, (cs
->ntypes
+ 1) *
1268 sizeof(*cs
->types
));
1269 if (newtypes
== NULL
) {
1270 SETERROR(REG_ESPACE
);
1273 cs
->types
= newtypes
;
1274 cs
->types
[cs
->ntypes
++] = wct
;
1278 - dupl - emit a duplicate of a bunch of sops
1279 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1281 static sopno
/* start of duplicate */
1282 dupl(p
, start
, finish
)
1284 sopno start
; /* from here */
1285 sopno finish
; /* to this less one */
1288 sopno len
= finish
- start
;
1290 assert(finish
>= start
);
1293 enlarge(p
, p
->ssize
+ len
); /* this many unexpected additions */
1294 assert(p
->ssize
>= p
->slen
+ len
);
1295 (void) memcpy((char *)(p
->strip
+ p
->slen
),
1296 (char *)(p
->strip
+ start
), (size_t)len
*sizeof(sop
));
1302 - doemit - emit a strip operator
1303 == static void doemit(struct parse *p, sop op, size_t opnd);
1305 * It might seem better to implement this as a macro with a function as
1306 * hard-case backup, but it's just too big and messy unless there are
1307 * some changes to the data structures. Maybe later.
1315 /* avoid making error situations worse */
1319 /* deal with oversize operands ("can't happen", more or less) */
1320 assert(opnd
< 1<<OPSHIFT
);
1322 /* deal with undersized strip */
1323 if (p
->slen
>= p
->ssize
)
1324 enlarge(p
, (p
->ssize
+1) / 2 * 3); /* +50% */
1325 assert(p
->slen
< p
->ssize
);
1327 /* finally, it's all reduced to the easy case */
1328 p
->strip
[p
->slen
++] = SOP(op
, opnd
);
1332 - doinsert - insert a sop into the strip
1333 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1336 doinsert(p
, op
, opnd
, pos
)
1346 /* avoid making error situations worse */
1351 EMIT(op
, opnd
); /* do checks, ensure space */
1352 assert(HERE() == sn
+1);
1355 /* adjust paren pointers */
1357 for (i
= 1; i
< NPAREN
; i
++) {
1358 if (p
->pbegin
[i
] >= pos
) {
1361 if (p
->pend
[i
] >= pos
) {
1366 memmove((char *)&p
->strip
[pos
+1], (char *)&p
->strip
[pos
],
1367 (HERE()-pos
-1)*sizeof(sop
));
1372 - dofwd - complete a forward reference
1373 == static void dofwd(struct parse *p, sopno pos, sop value);
1376 dofwd(p
, pos
, value
)
1381 /* avoid making error situations worse */
1385 assert(value
< 1<<OPSHIFT
);
1386 p
->strip
[pos
] = OP(p
->strip
[pos
]) | value
;
1390 - enlarge - enlarge the strip
1391 == static void enlarge(struct parse *p, sopno size);
1400 if (p
->ssize
>= size
)
1403 sp
= (sop
*)realloc(p
->strip
, size
*sizeof(sop
));
1405 SETERROR(REG_ESPACE
);
1413 - stripsnug - compact the strip
1414 == static void stripsnug(struct parse *p, struct re_guts *g);
1421 g
->nstates
= p
->slen
;
1422 g
->strip
= (sop
*)realloc((char *)p
->strip
, p
->slen
* sizeof(sop
));
1423 if (g
->strip
== NULL
) {
1424 SETERROR(REG_ESPACE
);
1425 g
->strip
= p
->strip
;
1430 - findmust - fill in must and mlen with longest mandatory literal string
1431 == static void findmust(struct parse *p, struct re_guts *g);
1433 * This algorithm could do fancy things like analyzing the operands of |
1434 * for common subsequences. Someday. This code is simple and finds most
1435 * of the interesting cases.
1437 * Note that must and mlen got initialized during setup.
1451 char buf
[MB_LEN_MAX
];
1455 /* avoid making error situations worse */
1460 * It's not generally safe to do a ``char'' substring search on
1461 * multibyte character strings, but it's safe for at least
1462 * UTF-8 (see RFC 3629).
1464 if (MB_CUR_MAX
> 1 &&
1465 strcmp(_CurrentRuneLocale
->__encoding
, "UTF-8") != 0)
1468 /* find the longest OCHAR sequence in strip */
1472 scan
= g
->strip
+ 1;
1476 case OCHAR
: /* sequence member */
1477 if (newlen
== 0) { /* new sequence */
1478 memset(&mbs
, 0, sizeof(mbs
));
1479 newstart
= scan
- 1;
1481 clen
= wcrtomb(buf
, OPND(s
), &mbs
);
1482 if (clen
== (size_t)-1)
1486 case OPLUS_
: /* things that don't break one */
1490 case OQUEST_
: /* things that must be skipped */
1492 offset
= altoffset(scan
, offset
);
1497 /* assert() interferes w debug printouts */
1498 if (OP(s
) != O_QUEST
&& OP(s
) != O_CH
&&
1503 } while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
);
1505 case OBOW
: /* things that break a sequence */
1512 if (newlen
> g
->mlen
) { /* ends one */
1516 g
->moffset
+= offset
;
1519 g
->moffset
= offset
;
1527 if (newlen
> g
->mlen
) { /* ends one */
1531 g
->moffset
+= offset
;
1534 g
->moffset
= offset
;
1543 case OANYOF
: /* may or may not invalidate offset */
1544 /* First, everything as OANY */
1545 if (newlen
> g
->mlen
) { /* ends one */
1549 g
->moffset
+= offset
;
1552 g
->moffset
= offset
;
1563 /* Anything here makes it impossible or too hard
1564 * to calculate the offset -- so we give up;
1565 * save the last known good offset, in case the
1566 * must sequence doesn't occur later.
1568 if (newlen
> g
->mlen
) { /* ends one */
1572 g
->moffset
+= offset
;
1574 g
->moffset
= offset
;
1580 } while (OP(s
) != OEND
);
1582 if (g
->mlen
== 0) { /* there isn't one */
1587 /* turn it into a character string */
1588 g
->must
= malloc((size_t)g
->mlen
+ 1);
1589 if (g
->must
== NULL
) { /* argh; just forget it */
1596 memset(&mbs
, 0, sizeof(mbs
));
1597 while (cp
< g
->must
+ g
->mlen
) {
1598 while (OP(s
= *scan
++) != OCHAR
)
1600 clen
= wcrtomb(cp
, OPND(s
), &mbs
);
1601 assert(clen
!= (size_t)-1);
1604 assert(cp
== g
->must
+ g
->mlen
);
1605 *cp
++ = '\0'; /* just on general principles */
1609 - altoffset - choose biggest offset among multiple choices
1610 == static int altoffset(sop *scan, int offset);
1612 * Compute, recursively if necessary, the largest offset among multiple
1616 altoffset(scan
, offset
)
1624 /* If we gave up already on offsets, return */
1631 while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
) {
1640 try = altoffset(scan
, try);
1647 if (OP(s
) != O_QUEST
&& OP(s
) != O_CH
&&
1650 } while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
);
1651 /* We must skip to the next position, or we'll
1652 * leave altoffset() too early.
1678 return largest
+offset
;
1682 - computejumps - compute char jumps for BM scan
1683 == static void computejumps(struct parse *p, struct re_guts *g);
1685 * This algorithm assumes g->must exists and is has size greater than
1686 * zero. It's based on the algorithm found on Computer Algorithms by
1689 * A char jump is the number of characters one needs to jump based on
1690 * the value of the character from the text that was mismatched.
1700 /* Avoid making errors worse */
1704 g
->charjump
= (int*) malloc((NC
+ 1) * sizeof(int));
1705 if (g
->charjump
== NULL
) /* Not a fatal error */
1707 /* Adjust for signed chars, if necessary */
1708 g
->charjump
= &g
->charjump
[-(CHAR_MIN
)];
1710 /* If the character does not exist in the pattern, the jump
1711 * is equal to the number of characters in the pattern.
1713 for (ch
= CHAR_MIN
; ch
< (CHAR_MAX
+ 1); ch
++)
1714 g
->charjump
[ch
] = g
->mlen
;
1716 /* If the character does exist, compute the jump that would
1717 * take us to the last character in the pattern equal to it
1718 * (notice that we match right to left, so that last character
1719 * is the first one that would be matched).
1721 for (mindex
= 0; mindex
< g
->mlen
; mindex
++)
1722 g
->charjump
[(int)g
->must
[mindex
]] = g
->mlen
- mindex
- 1;
1726 - computematchjumps - compute match jumps for BM scan
1727 == static void computematchjumps(struct parse *p, struct re_guts *g);
1729 * This algorithm assumes g->must exists and is has size greater than
1730 * zero. It's based on the algorithm found on Computer Algorithms by
1733 * A match jump is the number of characters one needs to advance based
1734 * on the already-matched suffix.
1735 * Notice that all values here are minus (g->mlen-1), because of the way
1736 * the search algorithm works.
1739 computematchjumps(p
, g
)
1743 int mindex
; /* General "must" iterator */
1744 int suffix
; /* Keeps track of matching suffix */
1745 int ssuffix
; /* Keeps track of suffixes' suffix */
1746 int* pmatches
; /* pmatches[k] points to the next i
1747 * such that i+1...mlen is a substring
1748 * of k+1...k+mlen-i-1
1751 /* Avoid making errors worse */
1755 pmatches
= (int*) malloc(g
->mlen
* sizeof(unsigned int));
1756 if (pmatches
== NULL
) {
1757 g
->matchjump
= NULL
;
1761 g
->matchjump
= (int*) malloc(g
->mlen
* sizeof(unsigned int));
1762 if (g
->matchjump
== NULL
) /* Not a fatal error */
1765 /* Set maximum possible jump for each character in the pattern */
1766 for (mindex
= 0; mindex
< g
->mlen
; mindex
++)
1767 g
->matchjump
[mindex
] = 2*g
->mlen
- mindex
- 1;
1769 /* Compute pmatches[] */
1770 for (mindex
= g
->mlen
- 1, suffix
= g
->mlen
; mindex
>= 0;
1771 mindex
--, suffix
--) {
1772 pmatches
[mindex
] = suffix
;
1774 /* If a mismatch is found, interrupting the substring,
1775 * compute the matchjump for that position. If no
1776 * mismatch is found, then a text substring mismatched
1777 * against the suffix will also mismatch against the
1780 while (suffix
< g
->mlen
1781 && g
->must
[mindex
] != g
->must
[suffix
]) {
1782 g
->matchjump
[suffix
] = MIN(g
->matchjump
[suffix
],
1783 g
->mlen
- mindex
- 1);
1784 suffix
= pmatches
[suffix
];
1788 /* Compute the matchjump up to the last substring found to jump
1789 * to the beginning of the largest must pattern prefix matching
1792 for (mindex
= 0; mindex
<= suffix
; mindex
++)
1793 g
->matchjump
[mindex
] = MIN(g
->matchjump
[mindex
],
1794 g
->mlen
+ suffix
- mindex
);
1796 ssuffix
= pmatches
[suffix
];
1797 while (suffix
< g
->mlen
) {
1798 while (suffix
<= ssuffix
&& suffix
< g
->mlen
) {
1799 g
->matchjump
[suffix
] = MIN(g
->matchjump
[suffix
],
1800 g
->mlen
+ ssuffix
- suffix
);
1803 if (suffix
< g
->mlen
)
1804 ssuffix
= pmatches
[ssuffix
];
1811 - pluscount - count + nesting
1812 == static sopno pluscount(struct parse *p, struct re_guts *g);
1814 static sopno
/* nesting depth */
1825 return(0); /* there may not be an OEND */
1827 scan
= g
->strip
+ 1;
1835 if (plusnest
> maxnest
)
1840 } while (OP(s
) != OEND
);